diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json
index 1b97ea68087..fcff1e84f52 100644
--- a/lib/cs/diagnosticMessages.generated.json
+++ b/lib/cs/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "Přistupující objekty musí být abstraktní nebo neabstraktní.",
"Add_0_to_existing_import_declaration_from_1_90015": "Přidat {0} k existující deklaraci importu z {1}",
"Add_async_modifier_to_containing_function_90029": "Přidat modifikátor async do obsahující funkce",
+ "Add_definite_assignment_assertion_to_property_0_95020": "Přidat kontrolní výraz jednoznačného přiřazení k vlastnosti {0}",
"Add_index_signature_for_property_0_90017": "Přidat signaturu indexu pro vlastnost {0}",
+ "Add_initializer_to_property_0_95019": "Přidat inicializační výraz k vlastnosti {0}",
"Add_missing_super_call_90001": "Přidat chybějící volání metody super()",
"Add_this_to_unresolved_variable_90008": "Přidat k nerozpoznané proměnné this.",
+ "Add_undefined_type_to_property_0_95018": "Přidat typ undefined k vlastnosti {0}",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Přidání souboru tsconfig.json vám pomůže uspořádat projekty, které obsahují jak soubory TypeScript, tak soubory JavaScript. Další informace najdete na adrese https://aka.ms/tsconfig.",
"Additional_Checks_6176": "Další kontroly",
"Advanced_Options_6178": "Upřesnit možnosti",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "Povolí experimentální podporu pro dekorátory ES7.",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Povolí experimentální podporu pro generování metadat typu pro dekorátory.",
"Enum_0_used_before_its_declaration_2450": "Výčet {0} se používá dříve, než se deklaruje.",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Deklarace výčtu jdou sloučit jenom s oborem názvů nebo jinými deklaracemi výčtu.",
"Enum_declarations_must_all_be_const_or_non_const_2473": "Všechny deklarace výčtu musí být konstantní nebo nekonstantní.",
"Enum_member_expected_1132": "Očekává se člen výčtu.",
"Enum_member_must_have_initializer_1061": "Člen výčtu musí mít inicializátor.",
diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json
index bff4663aa81..50dd290f58b 100644
--- a/lib/de/diagnosticMessages.generated.json
+++ b/lib/de/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "Beide Accessoren müssen abstrakt oder nicht abstrakt sein.",
"Add_0_to_existing_import_declaration_from_1_90015": "\"{0}\" der vorhandenen Importdeklaration aus \"{1}\" hinzufügen",
"Add_async_modifier_to_containing_function_90029": "Async-Modifizierer zur enthaltenden Funktion hinzufügen",
+ "Add_definite_assignment_assertion_to_property_0_95020": "Definitive Zuweisungsassertion zu Eigenschaft \"{0}\" hinzufügen",
"Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen",
+ "Add_initializer_to_property_0_95019": "Initialisierer zu Eigenschaft \"{0}\" hinzufügen",
"Add_missing_super_call_90001": "Fehlenden super()-Aufruf hinzufügen",
"Add_this_to_unresolved_variable_90008": "Der nicht aufgelösten Variablen \"this.\" hinzufügen",
+ "Add_undefined_type_to_property_0_95018": "undefined-Typ zu Eigenschaft \"{0}\" hinzufügen",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Das Hinzufügen einer \"tsconfig.json\"-Datei erleichtert die Organisation von Projekten, die sowohl TypeScript- als auch JavaScript-Dateien enthalten. Weitere Informationen finden Sie unter https://aka.ms/tsconfig.",
"Additional_Checks_6176": "Zusätzliche Überprüfungen",
"Advanced_Options_6178": "Erweiterte Optionen",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Decorators.",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Ermöglicht experimentelle Unterstützung zum Ausgeben von Typmetadaten für Decorators.",
"Enum_0_used_before_its_declaration_2450": "Enumeration \"{0}\", die vor der Deklaration wurde.",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enumerationsdeklarationen können nur mit Namespace- oder anderen Enumerationsdeklarationen zusammengeführt werden.",
"Enum_declarations_must_all_be_const_or_non_const_2473": "Enumerationsdeklarationen müssen alle konstant oder nicht konstant sein.",
"Enum_member_expected_1132": "Ein Enumerationsmember wurde erwartet.",
"Enum_member_must_have_initializer_1061": "Ein Enumerationsmember muss einen Initialisierer aufweisen.",
diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg
index a7d77e9ac02..321a2da7666 100644
--- a/lib/enu/diagnosticMessages.generated.json.lcg
+++ b/lib/enu/diagnosticMessages.generated.json.lcg
@@ -585,12 +585,24 @@
+ -
+
+
+
+
+
-
+ -
+
+
+
+
+
-
@@ -603,6 +615,12 @@
+ -
+
+
+
+
+
-
@@ -2289,6 +2307,12 @@
+ -
+
+
+
+
+
-
@@ -2565,6 +2589,12 @@
+ -
+
+
+
+
+
-
@@ -2805,6 +2835,12 @@
+ -
+
+
+
+
+
-
@@ -2877,6 +2913,12 @@
+ -
+
+
+
+
+
-
@@ -3063,6 +3105,12 @@
+ -
+
+
+
+
+
-
@@ -3963,9 +4011,9 @@
- -
+
-
-
+
@@ -4767,6 +4815,12 @@
+ -
+
+
+
+
+
-
@@ -5343,6 +5397,12 @@
+ -
+
+
+
+
+
-
diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json
index b44d3a14769..de0600305ff 100644
--- a/lib/es/diagnosticMessages.generated.json
+++ b/lib/es/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "Los descriptores de acceso deben ser los dos abstractos o los dos no abstractos.",
"Add_0_to_existing_import_declaration_from_1_90015": "Agregar \"{0}\" a una declaración de importación existente desde \"{1}\"",
"Add_async_modifier_to_containing_function_90029": "Agregar el modificador async a la función contenedora",
+ "Add_definite_assignment_assertion_to_property_0_95020": "Agregar aserción de asignación definitiva a la propiedad \"{0}\"",
"Add_index_signature_for_property_0_90017": "Agregar una signatura de índice para la propiedad \"{0}\"",
+ "Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"",
"Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta",
"Add_this_to_unresolved_variable_90008": "Agregar \"this.\" a una variable no resuelta",
+ "Add_undefined_type_to_property_0_95018": "Agregar un tipo \"undefined\" a la propiedad \"{0}\"",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Agregar un archivo tsconfig.json ayuda a organizar los proyectos que contienen archivos TypeScript y JavaScript. Más información en https://aka.ms/tsconfig.",
"Additional_Checks_6176": "Comprobaciones adicionales",
"Advanced_Options_6178": "Opciones avanzadas",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "Habilita la compatibilidad experimental con los elementos Decorator de ES7.",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita la compatibilidad experimental para emitir metadatos de tipo para los elementos Decorator.",
"Enum_0_used_before_its_declaration_2450": "Se ha usado la enumeración \"{0}\" antes de declararla.",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Las declaraciones de enumeración solo se pueden combinar con otras declaraciones de enumeración o de espacio de nombres.",
"Enum_declarations_must_all_be_const_or_non_const_2473": "Todas las declaraciones de enumeración deben ser de tipo const o no const.",
"Enum_member_expected_1132": "Se esperaba un miembro de enumeración.",
"Enum_member_must_have_initializer_1061": "El miembro de enumeración debe tener un inicializador.",
diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json
index 7142fcb0d7d..a4f72b1f119 100644
--- a/lib/fr/diagnosticMessages.generated.json
+++ b/lib/fr/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "Les accesseurs doivent être abstraits ou non abstraits.",
"Add_0_to_existing_import_declaration_from_1_90015": "Ajouter '{0}' à la déclaration d'importation existante de \"{1}\"",
"Add_async_modifier_to_containing_function_90029": "Ajouter le modificateur async dans la fonction conteneur",
+ "Add_definite_assignment_assertion_to_property_0_95020": "Ajouter une assertion d'assignation définie à la propriété '{0}'",
"Add_index_signature_for_property_0_90017": "Ajouter une signature d'index pour la propriété '{0}'",
+ "Add_initializer_to_property_0_95019": "Ajouter un initialiseur à la propriété '{0}'",
"Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'",
"Add_this_to_unresolved_variable_90008": "Ajouter 'this.' à la variable non résolue",
+ "Add_undefined_type_to_property_0_95018": "Ajouter un type 'undefined' à la propriété '{0}'",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "L'ajout d'un fichier tsconfig.json permet d'organiser les projets qui contiennent des fichiers TypeScript et JavaScript. En savoir plus sur https://aka.ms/tsconfig.",
"Additional_Checks_6176": "Vérifications supplémentaires",
"Advanced_Options_6178": "Options avancées",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "Active la prise en charge expérimentale des éléments décoratifs ES7.",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Active la prise en charge expérimentale pour l'émission des métadonnées de type pour les éléments décoratifs.",
"Enum_0_used_before_its_declaration_2450": "Enum '{0}' utilisé avant sa déclaration.",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Les déclarations enum ne peuvent fusionner qu'avec des espaces de noms ou d'autres déclarations enum.",
"Enum_declarations_must_all_be_const_or_non_const_2473": "Les déclarations d'enum doivent toutes être const ou non const.",
"Enum_member_expected_1132": "Membre enum attendu.",
"Enum_member_must_have_initializer_1061": "Un membre enum doit posséder un initialiseur.",
diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json
index 5bd0767bb28..84d5e41da48 100644
--- a/lib/it/diagnosticMessages.generated.json
+++ b/lib/it/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "Le funzioni di accesso devono essere tutte astratte o tutte non astratte.",
"Add_0_to_existing_import_declaration_from_1_90015": "Aggiungere '{0}' alla dichiarazione di importazione esistente da \"{1}\"",
"Add_async_modifier_to_containing_function_90029": "Aggiungere il modificatore async alla funzione contenitore",
+ "Add_definite_assignment_assertion_to_property_0_95020": "Aggiungere l'asserzione di assegnazione definita alla proprietà '{0}'",
"Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'",
+ "Add_initializer_to_property_0_95019": "Aggiungere l'inizializzatore alla proprietà '{0}'",
"Add_missing_super_call_90001": "Aggiungere la chiamata mancante a 'super()'",
"Add_this_to_unresolved_variable_90008": "Aggiungere 'this.' alla variabile non risolta",
+ "Add_undefined_type_to_property_0_95018": "Aggiungere il tipo 'undefined' alla proprietà '{0}'",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Aggiungere un file tsconfig.json per organizzare più facilmente progetti che contengono sia file TypeScript che JavaScript. Per altre informazioni, vedere https://aka.ms/tsconfig.",
"Additional_Checks_6176": "Controlli aggiuntivi",
"Advanced_Options_6178": "Opzioni avanzate",
diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json
index b1c1cf848f6..620e686eadf 100644
--- a/lib/ja/diagnosticMessages.generated.json
+++ b/lib/ja/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "アクセサーはどちらも抽象または非抽象である必要があります。",
"Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\" から既存のインポート宣言に '{0}' を追加する",
"Add_async_modifier_to_containing_function_90029": "含まれている関数に async 修飾子を追加します",
+ "Add_definite_assignment_assertion_to_property_0_95020": "プロパティ '{0}' に限定代入アサーションを追加します",
"Add_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加する",
+ "Add_initializer_to_property_0_95019": "プロパティ '{0}' に初期化子を追加します",
"Add_missing_super_call_90001": "欠落している 'super()' 呼び出しを追加する",
"Add_this_to_unresolved_variable_90008": "'this.' を未解決の変数に追加する",
+ "Add_undefined_type_to_property_0_95018": "プロパティ '{0}' に '未定義' の型を追加します",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json ファイルを追加すると、TypeScript ファイルと JavaScript ファイルの両方を含むプロジェクトを整理できます。詳細については、https://aka.ms/tsconfig をご覧ください。",
"Additional_Checks_6176": "追加のチェック",
"Advanced_Options_6178": "詳細オプション",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "ES7 デコレーター用の実験的なサポートを有効にします。",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "デコレーター用の型メタデータを発行するための実験的なサポートを有効にします。",
"Enum_0_used_before_its_declaration_2450": "列挙型 '{0}' は宣言の前に使用されました。",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "列挙型の宣言は、名前空間または他の列挙型の宣言とのみマージできます。",
"Enum_declarations_must_all_be_const_or_non_const_2473": "列挙型宣言は、すべてが定数、またはすべてが非定数でなければなりません。",
"Enum_member_expected_1132": "列挙型メンバーが必要です。",
"Enum_member_must_have_initializer_1061": "列挙型メンバーには初期化子が必要です。",
diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json
index f0b94025468..77b88307309 100644
--- a/lib/ko/diagnosticMessages.generated.json
+++ b/lib/ko/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "접근자는 모두 추상이거나 비추상이어야 합니다.",
"Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\"에서 기존 가져오기 선언에 '{0}' 추가",
"Add_async_modifier_to_containing_function_90029": "포함된 함수에 async 한정자 추가",
+ "Add_definite_assignment_assertion_to_property_0_95020": "'{0}' 속성에 한정된 할당 어설션 추가",
"Add_index_signature_for_property_0_90017": "'{0}' 속성에 대해 인덱스 시그니처 추가",
+ "Add_initializer_to_property_0_95019": "'{0}' 속성에 이니셜라이저 추가",
"Add_missing_super_call_90001": "누락된 'super()' 호출 추가",
"Add_this_to_unresolved_variable_90008": "확인되지 않은 변수에 'this.' 추가",
+ "Add_undefined_type_to_property_0_95018": "'{0}' 속성에 '정의되지 않은' 형식 추가",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json 파일을 추가하면 TypeScript 파일과 JavaScript 파일이 둘 다 포함된 프로젝트를 정리하는 데 도움이 됩니다. 자세한 내용은 https://aka.ms/tsconfig를 참조하세요.",
"Additional_Checks_6176": "추가 검사",
"Advanced_Options_6178": "고급 옵션",
diff --git a/lib/lib.es2018.d.ts b/lib/lib.es2018.d.ts
index 820467445eb..cfd5d0d60b2 100644
--- a/lib/lib.es2018.d.ts
+++ b/lib/lib.es2018.d.ts
@@ -19,3 +19,5 @@ and limitations under the License.
///
+///
+///
\ No newline at end of file
diff --git a/lib/lib.es2018.full.d.ts b/lib/lib.es2018.full.d.ts
index eef11659216..d4c90bed24a 100644
--- a/lib/lib.es2018.full.d.ts
+++ b/lib/lib.es2018.full.d.ts
@@ -19,7 +19,8 @@ and limitations under the License.
///
-
+///
+///
/////////////////////////////
diff --git a/lib/lib.esnext.promise.d.ts b/lib/lib.es2018.promise.d.ts
similarity index 100%
rename from lib/lib.esnext.promise.d.ts
rename to lib/lib.es2018.promise.d.ts
diff --git a/lib/lib.es2018.regexp.d.ts b/lib/lib.es2018.regexp.d.ts
new file mode 100644
index 00000000000..0c3358ef6af
--- /dev/null
+++ b/lib/lib.es2018.regexp.d.ts
@@ -0,0 +1,31 @@
+/*! *****************************************************************************
+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 RegExpMatchArray {
+ groups?: {
+ [key: string]: string
+ }
+}
+
+interface RegExpExecArray {
+ groups?: {
+ [key: string]: string
+ }
+}
\ No newline at end of file
diff --git a/lib/lib.esnext.d.ts b/lib/lib.esnext.d.ts
index 0947f078418..095e46de36f 100644
--- a/lib/lib.esnext.d.ts
+++ b/lib/lib.esnext.d.ts
@@ -21,4 +21,3 @@ and limitations under the License.
///
///
///
-///
diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts
index 5f047aa2673..ec1991fdc10 100644
--- a/lib/lib.esnext.full.d.ts
+++ b/lib/lib.esnext.full.d.ts
@@ -21,7 +21,6 @@ and limitations under the License.
///
///
///
-///
diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json
index 21691cd1e20..7f53cbf87fd 100644
--- a/lib/pl/diagnosticMessages.generated.json
+++ b/lib/pl/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "Obie metody dostępu muszą być abstrakcyjne lub nieabstrakcyjne.",
"Add_0_to_existing_import_declaration_from_1_90015": "Dodaj element „{0}” do istniejącej deklaracji importu z elementu „{1}”",
"Add_async_modifier_to_containing_function_90029": "Dodaj modyfikator asynchroniczny do funkcji zawierającej",
+ "Add_definite_assignment_assertion_to_property_0_95020": "Dodaj asercję określonego przypisania do właściwości „{0}”",
"Add_index_signature_for_property_0_90017": "Dodaj sygnaturę indeksu dla właściwości „{0}”",
+ "Add_initializer_to_property_0_95019": "Dodaj inicjator do właściwości „{0}”",
"Add_missing_super_call_90001": "Dodaj brakujące wywołanie „super()”",
"Add_this_to_unresolved_variable_90008": "Dodaj „this.” do nierozpoznanej zmiennej",
+ "Add_undefined_type_to_property_0_95018": "Dodaj typ „undefined” do właściwości „{0}”",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Dodanie pliku tsconfig.json pomoże w organizowaniu projektów, które zawierają pliki TypeScript i JavaScript. Dowiedz się więcej: https://aka.ms/tsconfig.",
"Additional_Checks_6176": "Dodatkowe kontrole",
"Advanced_Options_6178": "Opcje zaawansowane",
diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts
index 12fcad54070..20342511f15 100644
--- a/lib/protocol.d.ts
+++ b/lib/protocol.d.ts
@@ -23,10 +23,12 @@ declare namespace ts.server.protocol {
GeterrForProject = "geterrForProject",
SemanticDiagnosticsSync = "semanticDiagnosticsSync",
SyntacticDiagnosticsSync = "syntacticDiagnosticsSync",
+ SuggestionDiagnosticsSync = "suggestionDiagnosticsSync",
NavBar = "navbar",
Navto = "navto",
NavTree = "navtree",
NavTreeFull = "navtree-full",
+ /** @deprecated */
Occurrences = "occurrences",
DocumentHighlights = "documentHighlights",
Open = "open",
@@ -627,6 +629,7 @@ declare namespace ts.server.protocol {
openingBrace: string;
}
/**
+ * @deprecated
* Get occurrences request; value of command field is
* "occurrences". Return response giving spans that are relevant
* in the file at a given line and column.
@@ -634,6 +637,7 @@ declare namespace ts.server.protocol {
interface OccurrencesRequest extends FileLocationRequest {
command: CommandTypes.Occurrences;
}
+ /** @deprecated */
interface OccurrencesResponseItem extends FileSpan {
/**
* True if the occurrence is a write location, false otherwise.
@@ -644,6 +648,7 @@ declare namespace ts.server.protocol {
*/
isInString?: true;
}
+ /** @deprecated */
interface OccurrencesResponse extends Response {
body?: OccurrencesResponseItem[];
}
@@ -1541,6 +1546,12 @@ declare namespace ts.server.protocol {
interface SemanticDiagnosticsSyncResponse extends Response {
body?: Diagnostic[] | DiagnosticWithLinePosition[];
}
+ interface SuggestionDiagnosticsSyncRequest extends FileRequest {
+ command: CommandTypes.SuggestionDiagnosticsSync;
+ arguments: SuggestionDiagnosticsSyncRequestArgs;
+ }
+ type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs;
+ type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse;
/**
* Synchronous request for syntactic diagnostics of one file.
*/
@@ -1637,7 +1648,7 @@ declare namespace ts.server.protocol {
*/
text: string;
/**
- * The category of the diagnostic message, e.g. "error" vs. "warning"
+ * The category of the diagnostic message, e.g. "error", "warning", or "suggestion".
*/
category: string;
/**
@@ -1665,8 +1676,9 @@ declare namespace ts.server.protocol {
*/
diagnostics: Diagnostic[];
}
+ type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag";
/**
- * Event message for "syntaxDiag" and "semanticDiag" event types.
+ * Event message for DiagnosticEventKind event types.
* These events provide syntactic and semantic errors for a file.
*/
interface DiagnosticEvent extends Event {
diff --git a/lib/pt-BR/diagnosticMessages.generated.json b/lib/pt-BR/diagnosticMessages.generated.json
index c2770a52b40..dfd8c3e1e83 100644
--- a/lib/pt-BR/diagnosticMessages.generated.json
+++ b/lib/pt-BR/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "Acessadores devem ser abstratos ou não abstratos.",
"Add_0_to_existing_import_declaration_from_1_90015": "Adicionar '{0}' à declaração de importação existente de \"{1}\"",
"Add_async_modifier_to_containing_function_90029": "Adicione o modificador assíncrono que contém a função",
+ "Add_definite_assignment_assertion_to_property_0_95020": "Adicionar a asserção de atribuição definitiva à propriedade '{0}'",
"Add_index_signature_for_property_0_90017": "Adicionar assinatura de índice para a propriedade '{0}'",
+ "Add_initializer_to_property_0_95019": "Adicionar inicializador à propriedade '{0}'",
"Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente",
"Add_this_to_unresolved_variable_90008": "Adicionar 'this.' a uma variável não resolvida",
+ "Add_undefined_type_to_property_0_95018": "Adicionar tipo 'indefinido' à propriedade '{0}'",
"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",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "Habilita o suporte experimental para decoradores ES7.",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita o suporte experimental para a emissão de tipo de metadados para decoradores.",
"Enum_0_used_before_its_declaration_2450": "A enumeração '{0}' usada antes de sua declaração.",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações de enum apenas podem se mescladas com namespaces ou com outras declarações de enum.",
"Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações de enumeração devem ser const ou não const.",
"Enum_member_expected_1132": "Membro de enumeração esperado.",
"Enum_member_must_have_initializer_1061": "O membro de enumeração deve ter um inicializador.",
diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json
index aee384f8f7d..37adea40ac4 100644
--- a/lib/ru/diagnosticMessages.generated.json
+++ b/lib/ru/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "Методы доступа должны быть абстрактными или неабстрактными.",
"Add_0_to_existing_import_declaration_from_1_90015": "Добавьте \"{0}\" в существующее объявление импорта из \"{1}\"",
"Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию",
+ "Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного присваивания к свойству \"{0}\"",
"Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"",
+ "Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"",
"Add_missing_super_call_90001": "Добавьте отсутствующий вызов \"super()\"",
"Add_this_to_unresolved_variable_90008": "Добавьте \"this.\" к неразрешенной переменной",
+ "Add_undefined_type_to_property_0_95018": "Добавить тип \"undefined\" к свойству \"{0}\"",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Добавление файла tsconfig.json поможет организовать проекты, содержащие файлы TypeScript и JavaScript. Дополнительные сведения: https://aka.ms/tsconfig.",
"Additional_Checks_6176": "Дополнительные проверки",
"Advanced_Options_6178": "Дополнительные параметры",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "Включает экспериментальную поддержку для декораторов ES7.",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Включает экспериментальную поддержку для создания метаданных типа для декораторов.",
"Enum_0_used_before_its_declaration_2450": "Перечисление \"{0}\" использовано прежде, чем объявлено.",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Объявления перечислений можно объединять только с пространствами имен или другими объявлениями перечислений.",
"Enum_declarations_must_all_be_const_or_non_const_2473": "Все объявления перечислений должны иметь значение const или отличное от const.",
"Enum_member_expected_1132": "Ожидался элемент перечисления.",
"Enum_member_must_have_initializer_1061": "У элемента перечисления должен быть инициализатор.",
diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json
index cc088011fa5..67ff2b7106a 100644
--- a/lib/tr/diagnosticMessages.generated.json
+++ b/lib/tr/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "İki erişimci de soyut veya soyut olmayan olmalıdır.",
"Add_0_to_existing_import_declaration_from_1_90015": "'{0}' öğesini \"{1}\" konumundaki mevcut içeri aktarma bildirimine ekle",
"Add_async_modifier_to_containing_function_90029": "İçeren işleve zaman uyumsuz değiştirici ekle",
+ "Add_definite_assignment_assertion_to_property_0_95020": "'{0}' özelliğine belirli atama onayı ekle",
"Add_index_signature_for_property_0_90017": "'{0}' özelliği için dizin imzası ekle",
+ "Add_initializer_to_property_0_95019": "'{0}' özelliğine başlatıcı ekle",
"Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle",
"Add_this_to_unresolved_variable_90008": "Çözümlenmemiş değişkene 'this.' ekle",
+ "Add_undefined_type_to_property_0_95018": "'{0}' özelliğine 'undefined' türünü ekle",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Bir tsconfig.json dosyası eklemek, hem TypeScript hem de JavaScript dosyaları içeren projeleri düzenlemenize yardımcı olur. Daha fazla bilgi edinmek için bkz. https://aka.ms/tsconfig.",
"Additional_Checks_6176": "Ek Denetimler",
"Advanced_Options_6178": "Gelişmiş Seçenekler",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "ES7 dekoratörleri için deneysel desteği etkinleştirir.",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Dekoratörlere tür meta verisi gönderme için deneysel desteği etkinleştirir.",
"Enum_0_used_before_its_declaration_2450": "'{0}' sabit listesi, bildiriminden önce kullanıldı.",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enum bildirimleri yalnızca ad alanı veya diğer enum bildirimleri ile birleştirilebilir.",
"Enum_declarations_must_all_be_const_or_non_const_2473": "Sabit listesi bildirimlerinin tümü const veya const olmayan değerler olmalıdır.",
"Enum_member_expected_1132": "Sabit listesi üyesi bekleniyor.",
"Enum_member_must_have_initializer_1061": "Sabit listesi üyesi bir başlatıcıya sahip olmalıdır.",
diff --git a/lib/tsc.js b/lib/tsc.js
index b5c5051820e..17d65da71ff 100644
--- a/lib/tsc.js
+++ b/lib/tsc.js
@@ -54,8 +54,15 @@ var ts;
(function (DiagnosticCategory) {
DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
- DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message";
+ DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
+ DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
})(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
+ function diagnosticCategoryName(d, lowerCase) {
+ if (lowerCase === void 0) { lowerCase = true; }
+ var name = DiagnosticCategory[d.category];
+ return lowerCase ? name.toLowerCase() : name;
+ }
+ ts.diagnosticCategoryName = diagnosticCategoryName;
var ModuleResolutionKind;
(function (ModuleResolutionKind) {
ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
@@ -71,6 +78,37 @@ var ts;
ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext";
})(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
+ function _contextuallyTypePragmas(args) {
+ return args;
+ }
+ ts.commentPragmas = _contextuallyTypePragmas({
+ "reference": {
+ args: [
+ { name: "types", optional: true, captureSpan: true },
+ { name: "path", optional: true, captureSpan: true },
+ { name: "no-default-lib", optional: true }
+ ],
+ kind: 1
+ },
+ "amd-dependency": {
+ args: [{ name: "path" }, { name: "name", optional: true }],
+ kind: 1
+ },
+ "amd-module": {
+ args: [{ name: "name" }],
+ kind: 1
+ },
+ "ts-check": {
+ kind: 2
+ },
+ "ts-nocheck": {
+ kind: 2
+ },
+ "jsx": {
+ args: [{ name: "factory" }],
+ kind: 4
+ },
+ });
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -132,7 +170,7 @@ var ts;
var ts;
(function (ts) {
ts.versionMajorMinor = "2.8";
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".0";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -1190,19 +1228,21 @@ var ts;
}
ts.equalOwnProperties = equalOwnProperties;
function arrayToMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = createMap();
for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
var value = array_6[_i];
- result.set(makeKey(value), makeValue ? makeValue(value) : value);
+ result.set(makeKey(value), makeValue(value));
}
return result;
}
ts.arrayToMap = arrayToMap;
function arrayToNumericMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = [];
for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
var value = array_7[_i];
- result[makeKey(value)] = makeValue ? makeValue(value) : value;
+ result[makeKey(value)] = makeValue(value);
}
return result;
}
@@ -1211,6 +1251,20 @@ var ts;
return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; });
}
ts.arrayToSet = arrayToSet;
+ function arrayToMultiMap(values, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
+ var result = createMultiMap();
+ for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
+ var value = values_1[_i];
+ result.add(makeKey(value), makeValue(value));
+ }
+ return result;
+ }
+ ts.arrayToMultiMap = arrayToMultiMap;
+ function group(values, getGroupId) {
+ return arrayFrom(arrayToMultiMap(values, getGroupId).values());
+ }
+ ts.group = group;
function cloneMap(map) {
var clone = createMap();
copyEntries(map, clone);
@@ -1268,15 +1322,6 @@ var ts;
}
}
}
- function group(values, getGroupId) {
- var groupIdToGroup = createMultiMap();
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- groupIdToGroup.add(getGroupId(value), value);
- }
- return arrayFrom(groupIdToGroup.values());
- }
- ts.group = group;
function isArray(value) {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
@@ -1384,7 +1429,6 @@ var ts;
return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; });
}
ts.formatStringFromArgs = formatStringFromArgs;
- ts.localizedDiagnosticMessages = undefined;
function getLocaleSpecificMessage(message) {
return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
}
@@ -2150,7 +2194,7 @@ var ts;
}
includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive);
var _loop_2 = function (includeBasePath) {
- if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
+ if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
basePaths.push(includeBasePath);
}
};
@@ -2493,7 +2537,7 @@ var ts;
}
ts.matchedText = matchedText;
function findBestPatternMatch(values, getPattern, candidate) {
- var matchedValue = undefined;
+ var matchedValue;
var longestMatchPrefixLength = -1;
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
var v = values_2[_i];
@@ -3606,6 +3650,7 @@ var ts;
Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
+ Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
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}'."),
@@ -3677,7 +3722,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}'."),
- 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.Message, "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."),
+ 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}'."),
Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
@@ -3850,7 +3895,7 @@ var ts;
Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
- Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."),
+ Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
@@ -3894,6 +3939,7 @@ var ts;
Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."),
+ Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."),
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."),
@@ -3973,10 +4019,15 @@ var ts;
JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
+ JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
+ File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
+ This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
+ Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
+ JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
@@ -4017,6 +4068,9 @@ var ts;
Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
+ Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
+ Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
+ Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
};
})(ts || (ts = {}));
var ts;
@@ -6034,8 +6088,7 @@ var ts;
}
ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
function isAmbientModule(node) {
- return node && node.kind === 237 &&
- (node.name.kind === 9 || isGlobalScopeAugmentation(node));
+ return ts.isModuleDeclaration(node) && (node.name.kind === 9 || isGlobalScopeAugmentation(node));
}
ts.isAmbientModule = isAmbientModule;
function isModuleWithStringLiteralName(node) {
@@ -6064,18 +6117,19 @@ var ts;
}
ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
function isExternalModuleAugmentation(node) {
- if (!node || !isAmbientModule(node)) {
- return false;
- }
+ return isAmbientModule(node) && isModuleAugmentationExternal(node);
+ }
+ ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ function isModuleAugmentationExternal(node) {
switch (node.parent.kind) {
case 272:
return ts.isExternalModule(node.parent);
case 238:
- return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
+ return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
}
return false;
}
- ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
function isEffectiveExternalModule(node, compilerOptions) {
return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
}
@@ -7275,14 +7329,7 @@ var ts;
}
ts.isNodeDescendantOf = isNodeDescendantOf;
function isDeclarationName(name) {
- switch (name.kind) {
- case 71:
- case 9:
- case 8:
- return ts.isDeclaration(name.parent) && name.parent.name === name;
- default:
- return false;
- }
+ return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
}
ts.isDeclarationName = isDeclarationName;
function isAnyDeclarationName(name) {
@@ -7395,38 +7442,6 @@ var ts;
return undefined;
}
ts.getAncestor = getAncestor;
- function getFileReferenceFromReferencePath(comment, commentRange) {
- var simpleReferenceRegEx = /^\/\/\/\s*= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
}
ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
function textSpanIntersectsWith(span, start, length) {
- var end = start + length;
- return start <= textSpanEnd(span) && end >= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
}
ts.textSpanIntersectsWith = textSpanIntersectsWith;
function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
@@ -8896,12 +8898,9 @@ var ts;
}
ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
function textSpanIntersection(span1, span2) {
- var intersectStart = Math.max(span1.start, span2.start);
- var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
- if (intersectStart <= intersectEnd) {
- return createTextSpanFromBounds(intersectStart, intersectEnd);
- }
- return undefined;
+ var start = Math.max(span1.start, span2.start);
+ var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
+ return start <= end ? createTextSpanFromBounds(start, end) : undefined;
}
ts.textSpanIntersection = textSpanIntersection;
function createTextSpan(start, length) {
@@ -11193,7 +11192,8 @@ var ts;
sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
sourceFile.flags = contextFlags;
nextToken();
- processReferenceComments(sourceFile);
+ processCommentPragmas(sourceFile, sourceText);
+ processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
sourceFile.statements = parseList(0, parseStatement);
ts.Debug.assert(token() === 1);
sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
@@ -11206,6 +11206,9 @@ var ts;
fixupParentReferences(sourceFile);
}
return sourceFile;
+ function reportPragmaDiagnostic(pos, end, diagnostic) {
+ parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
+ }
}
function addJSDocComment(node) {
var comments = ts.getJSDocCommentRanges(node, sourceFile.text);
@@ -13461,8 +13464,8 @@ var ts;
var fullStart = scanner.getStartPos();
parseExpected(27);
if (token() === 29) {
- parseExpected(29);
var node_1 = createNode(258, fullStart);
+ scanJsxText();
return finishNode(node_1);
}
var tagName = parseJsxElementName();
@@ -13501,7 +13504,9 @@ var ts;
}
function parseJsxExpression(inExpressionContext) {
var node = createNode(263);
- parseExpected(17);
+ if (!parseExpected(17)) {
+ return undefined;
+ }
if (token() !== 18) {
node.dotDotDotToken = parseOptionalToken(24);
node.expression = parseAssignmentExpressionOrHigher();
@@ -13925,7 +13930,7 @@ var ts;
parseExpected(88);
var awaitToken = parseOptionalToken(121);
parseExpected(19);
- var initializer = undefined;
+ var initializer;
if (token() !== 25) {
if (token() === 104 || token() === 110 || token() === 76) {
initializer = parseVariableDeclarationList(true);
@@ -14939,84 +14944,6 @@ var ts;
parseSemicolon();
return finishNode(node);
}
- function processReferenceComments(sourceFile) {
- var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText);
- var referencedFiles = [];
- var typeReferenceDirectives = [];
- var amdDependencies = [];
- var amdModuleName;
- var checkJsDirective = undefined;
- while (true) {
- var kind = triviaScanner.scan();
- if (kind !== 2) {
- if (ts.isTrivia(kind)) {
- continue;
- }
- else {
- break;
- }
- }
- var range = {
- kind: triviaScanner.getToken(),
- pos: triviaScanner.getTokenPos(),
- end: triviaScanner.getTextPos(),
- };
- var comment = sourceText.substring(range.pos, range.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range);
- if (referencePathMatchResult) {
- var fileReference = referencePathMatchResult.fileReference;
- sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var diagnosticMessage = referencePathMatchResult.diagnosticMessage;
- if (fileReference) {
- if (referencePathMatchResult.isTypeReferenceDirective) {
- typeReferenceDirectives.push(fileReference);
- }
- else {
- referencedFiles.push(fileReference);
- }
- }
- if (diagnosticMessage) {
- parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage));
- }
- }
- else {
- var amdModuleNameRegEx = /^\/\/\/\s* context.checkJsDirective.pos) {
+ context.checkJsDirective = {
+ enabled: key === "ts-check",
+ end: entry.range.end,
+ pos: entry.range.pos
+ };
+ }
+ });
+ break;
+ }
+ case "jsx": return;
+ default: ts.Debug.fail("Unhandled pragma kind");
+ }
+ });
+ }
+ ts.processPragmasIntoFields = processPragmasIntoFields;
+ var namedArgRegExCache = ts.createMap();
+ function getNamedArgRegEx(name) {
+ if (namedArgRegExCache.has(name)) {
+ return namedArgRegExCache.get(name);
+ }
+ var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
+ namedArgRegExCache.set(name, result);
+ return result;
+ }
+ var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
+ var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
+ function extractPragmas(pragmas, range, text) {
+ var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text);
+ if (tripleSlash) {
+ var name = tripleSlash[1].toLowerCase();
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & 1)) {
+ return;
+ }
+ if (pragma.args) {
+ var argument = {};
+ for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
+ var arg = _a[_i];
+ var matcher = getNamedArgRegEx(arg.name);
+ var matchResult = matcher.exec(text);
+ if (!matchResult && !arg.optional) {
+ return;
+ }
+ else if (matchResult) {
+ if (arg.captureSpan) {
+ var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
+ argument[arg.name] = {
+ value: matchResult[3],
+ pos: startPos,
+ end: startPos + matchResult[3].length
+ };
+ }
+ else {
+ argument[arg.name] = matchResult[3];
+ }
+ }
+ }
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ }
+ else {
+ pragmas.push({ name: name, args: { arguments: {}, range: range } });
+ }
+ return;
+ }
+ var singleLine = singleLinePragmaRegEx.exec(text);
+ if (singleLine) {
+ return addPragmaForMatch(pragmas, range, 2, singleLine);
+ }
+ var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim;
+ var multiLineMatch;
+ while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
+ addPragmaForMatch(pragmas, range, 4, multiLineMatch);
+ }
+ }
+ function addPragmaForMatch(pragmas, range, kind, match) {
+ if (!match)
+ return;
+ var name = match[1].toLowerCase();
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & kind)) {
+ return;
+ }
+ var args = match[2];
+ var argument = getNamedPragmaArguments(pragma, args);
+ if (argument === "fail")
+ return;
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ return;
+ }
+ function getNamedPragmaArguments(pragma, text) {
+ if (!text)
+ return {};
+ if (!pragma.args)
+ return {};
+ var args = text.split(/\s+/);
+ var argMap = {};
+ for (var i = 0; i < pragma.args.length; i++) {
+ var argument = pragma.args[i];
+ if (!args[i] && !argument.optional) {
+ return "fail";
+ }
+ if (argument.captureSpan) {
+ return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
+ }
+ argMap[argument.name] = args[i];
+ }
+ return argMap;
+ }
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -16142,7 +16263,7 @@ var ts;
ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
}
- return ts.getEscapedTextOfIdentifierOrLiteral(name);
+ return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
switch (node.kind) {
case 154:
@@ -16236,7 +16357,12 @@ var ts;
}
}
addDeclarationToSymbol(symbol, node, includes);
- symbol.parent = parent;
+ if (symbol.parent) {
+ ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ symbol.parent = parent;
+ }
return symbol;
}
function declareModuleMember(node, symbolFlags, symbolExcludes) {
@@ -17201,7 +17327,7 @@ var ts;
if (ts.hasModifier(node, 1)) {
errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
- if (ts.isExternalModuleAugmentation(node)) {
+ if (ts.isModuleAugmentationExternal(node)) {
declareModuleSymbol(node);
}
else {
@@ -17216,9 +17342,7 @@ var ts;
}
}
var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639);
- if (pattern) {
- (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol });
- }
+ file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
}
}
else {
@@ -17539,7 +17663,7 @@ var ts;
seenThisKeyword = true;
return;
case 160:
- return checkTypePredicate(node);
+ break;
case 147:
return bindTypeParameter(node);
case 148:
@@ -17653,16 +17777,6 @@ var ts;
function bindAnonymousTypeWorker(node) {
return bindAnonymousDeclaration(node, 2048, "__type");
}
- function checkTypePredicate(node) {
- var parameterName = node.parameterName, type = node.type;
- if (parameterName && parameterName.kind === 71) {
- checkStrictModeIdentifier(parameterName);
- }
- if (parameterName && parameterName.kind === 173) {
- seenThisKeyword = true;
- }
- bind(type);
- }
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (ts.isExternalModule(file)) {
@@ -19065,8 +19179,10 @@ var ts;
}
ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
- var directoryToModuleNameMap = ts.createMap();
- var moduleNameToDirectoryMap = ts.createMap();
+ return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName);
+ }
+ ts.createModuleResolutionCache = createModuleResolutionCache;
+ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
function getOrCreateCacheForDirectory(directoryName) {
var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
@@ -19132,7 +19248,7 @@ var ts;
}
}
}
- ts.createModuleResolutionCache = createModuleResolutionCache;
+ ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
@@ -19143,7 +19259,7 @@ var ts;
var result = perFolderCache && perFolderCache.get(moduleName);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
}
else {
@@ -19265,7 +19381,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
}
- var matchedPattern = undefined;
+ var matchedPattern;
if (state.compilerOptions.paths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
@@ -19677,6 +19793,7 @@ var ts;
}
return packageName;
}
+ ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage;
function getPackageNameFromAtTypesDirectory(mangledName) {
var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
if (withoutAtTypePrefix !== mangledName) {
@@ -19695,7 +19812,7 @@ var ts;
var result = cache && cache.get(containingDirectory);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
}
@@ -19969,7 +20086,7 @@ var ts;
node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement);
return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined;
},
- getJsxIntrinsicTagNames: getJsxIntrinsicTagNames,
+ getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
isOptionalParameter: function (node) {
node = ts.getParseTreeNode(node, ts.isParameter);
return node ? isOptionalParameter(node) : false;
@@ -20006,7 +20123,7 @@ var ts;
resolveName: function (name, location, meaning, excludeGlobals) {
return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals);
},
- getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); },
+ getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
@@ -20018,13 +20135,13 @@ var ts;
node = ts.getParseTreeNode(node, ts.isTypeNode);
return node && getTypeArgumentConstraint(node);
},
+ getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; },
};
var tupleTypes = [];
var unionTypes = ts.createMap();
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
- var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4, "unknown");
@@ -20086,6 +20203,7 @@ var ts;
var anyArrayType;
var autoArrayType;
var anyReadonlyArrayType;
+ var deferredGlobalNonNullableTypeAlias;
var deferredGlobalESSymbolConstructorSymbol;
var deferredGlobalESSymbolType;
var deferredGlobalTypedPropertyDescriptorType;
@@ -20099,9 +20217,6 @@ var ts;
var deferredGlobalAsyncIteratorType;
var deferredGlobalAsyncIterableIteratorType;
var deferredGlobalTemplateStringsArrayType;
- var deferredJsxElementClassType;
- var deferredJsxElementType;
- var deferredJsxStatelessElementType;
var deferredNodes;
var deferredUnusedIdentifierNodes;
var flowLoopStart = 0;
@@ -20128,6 +20243,18 @@ var ts;
var potentialNewTargetCollisions = [];
var awaitedTypeStack = [];
var diagnostics = ts.createDiagnosticCollection();
+ var suggestionDiagnostics = ts.createMultiMap();
+ function addSuggestionDiagnostic(diag) {
+ suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
+ }
+ function addErrorOrSuggestionDiagnostic(isError, diag) {
+ if (isError) {
+ diagnostics.add(diag);
+ }
+ else {
+ addSuggestionDiagnostic(diag);
+ }
+ }
var typeofEQFacts = ts.createMapFromTemplate({
string: 1,
number: 2,
@@ -20156,11 +20283,6 @@ var ts;
var typeofType = createTypeofType();
var _jsxNamespace;
var _jsxFactoryEntity;
- var _jsxElementPropertiesName;
- var _hasComputedJsxElementPropertiesName = false;
- var _jsxElementChildrenPropertyName;
- var _hasComputedJsxElementChildrenPropertyName = false;
- var jsxTypes = ts.createUnderscoreEscapedMap();
var subtypeRelation = ts.createMap();
var assignableRelation = ts.createMap();
var definitelyAssignableRelation = ts.createMap();
@@ -20305,7 +20427,23 @@ var ts;
};
}
}
- function getJsxNamespace() {
+ function getJsxNamespace(location) {
+ if (location) {
+ var file = ts.getSourceFileOfNode(location);
+ if (file) {
+ if (file.localJsxNamespace) {
+ return file.localJsxNamespace;
+ }
+ var jsxPragma = file.pragmas.get("jsx");
+ if (jsxPragma) {
+ var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
+ file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
+ if (file.localJsxFactory) {
+ return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
+ }
+ }
+ }
+ }
if (!_jsxNamespace) {
_jsxNamespace = "React";
if (compilerOptions.jsxFactory) {
@@ -21123,7 +21261,15 @@ var ts;
combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
symbolFromModule || symbolFromVariable;
if (!symbol) {
- error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name));
+ var moduleName = getFullyQualifiedName(moduleSymbol);
+ var declarationName = ts.declarationNameToString(name);
+ var suggestion = getSuggestionForNonexistentModule(name, targetSymbol);
+ if (suggestion !== undefined) {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion);
+ }
+ else {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
+ }
}
return symbol;
}
@@ -21308,6 +21454,9 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
+ if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) {
+ addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
+ }
return getMergedSymbol(sourceFile.symbol);
}
if (moduleNotFoundError) {
@@ -21326,10 +21475,8 @@ var ts;
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
}
- else if (noImplicitAny && moduleNotFoundError) {
- var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name);
- errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName);
- diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo));
+ else {
+ addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
}
return undefined;
}
@@ -21350,6 +21497,11 @@ var ts;
}
return undefined;
}
+ function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) {
+ var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
+ var errorInfo = packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name));
+ return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
+ }
function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol;
}
@@ -21605,11 +21757,19 @@ var ts;
function getQualifiedLeftMeaning(rightMeaning) {
return rightMeaning === 107455 ? 107455 : 1920;
}
- function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) {
+ function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
+ if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
return undefined;
}
- var visitedSymbolTables = [];
+ var id = "" + getSymbolId(symbol);
+ var visitedSymbolTables;
+ if (visitedSymbolTablesMap.has(id)) {
+ visitedSymbolTables = visitedSymbolTablesMap.get(id);
+ }
+ else {
+ visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
+ }
return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
@@ -21621,7 +21781,7 @@ var ts;
}
function canQualifySymbol(symbolFromSymbolTable, meaning) {
return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
- !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing);
+ !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
}
function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) &&
@@ -21635,6 +21795,7 @@ var ts;
return ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
if (symbolFromSymbolTable.flags & 2097152
&& symbolFromSymbolTable.escapedName !== "export="
+ && symbolFromSymbolTable.escapedName !== "default"
&& !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
&& (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) {
var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
@@ -21825,6 +21986,7 @@ var ts;
}
}
function typeToString(type, enclosingDeclaration, flags, writer) {
+ if (flags === void 0) { flags = 1048576; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960, writer);
ts.Debug.assert(typeNode !== undefined, "should always get typenode");
@@ -21950,6 +22112,9 @@ var ts;
}
if (type.flags & 1024) {
if (!(context.flags & 1048576)) {
+ if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
+ return ts.createTypeQueryNode(symbolToName(type.symbol, context, 107455, false));
+ }
if (context.tracker.reportInaccessibleUniqueSymbolError) {
context.tracker.reportInaccessibleUniqueSymbolError();
}
@@ -22030,8 +22195,8 @@ var ts;
if (type.flags & 2097152) {
var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
- var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
- var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
+ var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
+ var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
if (type.flags & 4194304) {
@@ -22189,7 +22354,7 @@ var ts;
}
}
}
- var entityName = undefined;
+ var entityName = void 0;
var nameIdentifier = symbolToTypeReferenceName(type.symbol);
if (qualifiedName) {
ts.Debug.assert(!qualifiedName.right);
@@ -22617,8 +22782,8 @@ var ts;
return "(Anonymous function)";
}
}
- if (symbol.syntheticLiteralTypeOrigin) {
- var stringValue = symbol.syntheticLiteralTypeOrigin.value;
+ if (symbol.nameType && symbol.nameType.flags & 32) {
+ var stringValue = symbol.nameType.value;
if (!ts.isIdentifierText(stringValue, compilerOptions.target)) {
return "\"" + ts.escapeString(stringValue, 34) + "\"";
}
@@ -22881,7 +23046,7 @@ var ts;
parentType = getNonNullableType(parentType);
}
var propType = getTypeOfPropertyOfType(parentType, text);
- var declaredType = propType && getApparentTypeForLocation(propType, declaration.name);
+ var declaredType = propType && getConstraintForLocation(propType, declaration.name);
type = declaredType && getFlowTypeOfReference(declaration, declaredType) ||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) ||
getIndexTypeOfType(parentType, 0);
@@ -23967,8 +24132,17 @@ var ts;
error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3);
lateSymbol = createSymbol(0, memberName, 1024);
}
+ var symbolLinks_1 = getSymbolLinks(lateSymbol);
+ if (!symbolLinks_1.nameType) {
+ symbolLinks_1.nameType = type;
+ }
addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
- lateSymbol.parent = parent;
+ if (lateSymbol.parent) {
+ ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ lateSymbol.parent = parent;
+ }
return links.resolvedSymbol = lateSymbol;
}
}
@@ -24151,7 +24325,7 @@ var ts;
}
return [signature];
}
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true);
if (!match) {
@@ -24163,7 +24337,7 @@ var ts;
}
function getUnionSignatures(types, kind) {
var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); });
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
var signature = _a[_i];
@@ -24279,7 +24453,7 @@ var ts;
}
else {
var members = emptySymbols;
- var stringIndexInfo = undefined;
+ var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
}
@@ -24359,11 +24533,10 @@ var ts;
if (typeof propertySymbolOrIndex === "object") {
propertySymbol = propertySymbolOrIndex;
}
- var iterationMapper = createTypeMapper([typeParameter], [t]);
- var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper;
+ var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t]));
var propType = instantiateType(templateType, templateMapper);
if (t.flags & 32) {
- var propName = ts.escapeLeadingUnderscores(t.value);
+ var propName = getLateBoundNameFromType(t);
var modifiersProp = getPropertyOfType(modifiersType, propName);
var isOptional = !!(templateModifiers & 4 ||
!(templateModifiers & 8) && modifiersProp && modifiersProp.flags & 16777216);
@@ -24377,7 +24550,7 @@ var ts;
prop.syntheticOrigin = propertySymbol;
prop.declarations = propertySymbol.declarations;
}
- prop.syntheticLiteralTypeOrigin = t;
+ prop.nameType = t;
members.set(propName, prop);
}
else if (t.flags & (1 | 2)) {
@@ -24547,16 +24720,14 @@ var ts;
return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined;
}
function getDefaultConstraintOfConditionalType(type) {
- return getUnionType([type.trueType, type.falseType]);
+ return getUnionType([getTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]);
}
function getConstraintOfDistributiveConditionalType(type) {
- if (isDistributiveConditionalType(type)) {
+ if (type.root.isDistributive) {
var constraint = getConstraintOfType(type.checkType);
if (constraint) {
- var target = type.target || type;
- var mapper = createTypeMapper([target.checkType], [constraint]);
- var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper;
- return instantiateType(target, combinedMapper);
+ var mapper = createTypeMapper([type.root.checkType], [constraint]);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
}
}
return undefined;
@@ -24564,17 +24735,23 @@ var ts;
function getConstraintOfConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
- function getBaseConstraintOfType(type) {
+ function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) {
if (type.flags & (7372800 | 393216)) {
var constraint = getResolvedBaseConstraint(type);
if (constraint !== noConstraintType && constraint !== circularConstraintType) {
return constraint;
}
}
- else if (type.flags & 524288) {
+ }
+ function getBaseConstraintOfType(type) {
+ var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type);
+ if (!constraint && type.flags & 524288) {
return stringType;
}
- return undefined;
+ return constraint;
+ }
+ function getBaseConstraintOrType(type) {
+ return getBaseConstraintOfType(type) || type;
}
function hasNonCircularBaseConstraint(type) {
return getResolvedBaseConstraint(type) !== circularConstraintType;
@@ -24633,7 +24810,8 @@ var ts;
return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 2097152) {
- return getBaseConstraint(getConstraintOfConditionalType(t));
+ var constraint = getConstraintOfConditionalType(t);
+ return constraint && getBaseConstraint(constraint);
}
if (t.flags & 4194304) {
return getBaseConstraint(t.substitute);
@@ -24725,7 +24903,7 @@ var ts;
}
var propTypes = [];
var declarations = [];
- var commonType = undefined;
+ var commonType;
for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
var prop = props_1[_b];
if (prop.declarations) {
@@ -24941,7 +25119,7 @@ var ts;
var parameters = [];
var hasLiteralTypes = false;
var minArgumentCount = 0;
- var thisParameter = undefined;
+ var thisParameter = void 0;
var hasThisParameter = void 0;
var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
@@ -25657,11 +25835,6 @@ var ts;
var symbol = getGlobalSymbol(name, 793064, undefined);
return symbol && getTypeOfGlobalSymbol(symbol, arity);
}
- function getExportedTypeFromNamespace(namespace, name) {
- var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined);
- var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064);
- return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol);
- }
function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
}
@@ -25761,6 +25934,8 @@ var ts;
}
else if (flags & 1) {
includes |= 1;
+ if (type === wildcardType)
+ includes |= 4096;
}
else if (!strictNullChecks && flags & 12288) {
if (flags & 4096)
@@ -25868,7 +26043,7 @@ var ts;
var typeSet = [];
var includes = addTypesToUnion(typeSet, 0, types);
if (includes & 1) {
- return anyType;
+ return includes & 4096 ? wildcardType : anyType;
}
switch (unionReduction) {
case 1:
@@ -25952,6 +26127,8 @@ var ts;
}
else if (flags & 1) {
includes |= 1;
+ if (type === wildcardType)
+ includes |= 4096;
}
else if (flags & 16384) {
includes |= 8;
@@ -25990,7 +26167,7 @@ var ts;
return neverType;
}
if (includes & 1) {
- return anyType;
+ return includes & 4096 ? wildcardType : anyType;
}
if (includes & 1024 && !(includes & 512)) {
typeSet.push(emptyObjectType);
@@ -26030,19 +26207,30 @@ var ts;
return type.resolvedIndexType;
}
function getLiteralTypeFromPropertyName(prop) {
- return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ?
- neverType :
- getLiteralType(ts.symbolName(prop));
+ var links = getSymbolLinks(prop);
+ if (!links.nameType) {
+ if (links.target) {
+ ts.Debug.assert(links.target.escapedName === prop.escapedName, "Target symbol and symbol do not have the same name");
+ links.nameType = getLiteralTypeFromPropertyName(links.target);
+ }
+ else {
+ links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ?
+ neverType :
+ getLiteralType(ts.symbolName(prop));
+ }
+ }
+ return links.nameType;
}
function getLiteralTypeFromPropertyNames(type) {
return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName));
}
function getIndexType(type) {
- return maybeTypeOfKind(type, 7372800) ? getIndexTypeForGenericType(type) :
- ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) :
- type === wildcardType ? wildcardType :
- type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType :
- getLiteralTypeFromPropertyNames(type);
+ return type.flags & 262144 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) :
+ maybeTypeOfKind(type, 7372800) ? getIndexTypeForGenericType(type) :
+ ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) :
+ type === wildcardType ? wildcardType :
+ type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType :
+ getLiteralTypeFromPropertyNames(type);
}
function getIndexTypeOrString(type) {
var indexType = getIndexType(type);
@@ -26188,10 +26376,13 @@ var ts;
}
function substituteIndexedMappedType(objectType, type) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper;
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
}
function getIndexedAccessType(objectType, indexType, accessNode) {
+ if (objectType === wildcardType || indexType === wildcardType) {
+ return wildcardType;
+ }
if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 184) && isGenericObjectType(objectType)) {
if (objectType.flags & 1) {
return objectType;
@@ -26240,54 +26431,45 @@ var ts;
function getActualTypeParameter(type) {
return type.flags & 4194304 ? type.typeParameter : type;
}
- function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) {
- var type = createType(2097152);
- type.checkType = checkType;
- type.extendsType = extendsType;
- type.trueType = trueType;
- type.falseType = falseType;
- type.inferTypeParameters = inferTypeParameters;
- type.target = target;
- type.mapper = mapper;
- type.aliasSymbol = aliasSymbol;
- type.aliasTypeArguments = aliasTypeArguments;
- return type;
- }
- function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) {
- var extendsType = instantiateType(baseExtendsType, mapper);
- if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) {
- return instantiateType(baseFalseType, mapper);
+ function getConditionalType(root, mapper) {
+ var checkType = instantiateType(root.checkType, mapper);
+ var extendsType = instantiateType(root.extendsType, mapper);
+ if (checkType === wildcardType || extendsType === wildcardType) {
+ return wildcardType;
}
- var combinedMapper;
- if (inferTypeParameters) {
- var inferences = ts.map(inferTypeParameters, createInferenceInfo);
- inferTypes(inferences, checkType, extendsType, 8 | 16);
- var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; });
- var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes);
- combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper;
- }
- if (checkType.flags & 1 || (checkType.flags & 16384 && !(extendsType.flags & 16384))) {
- return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]);
- }
- var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType;
- if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) {
- return instantiateType(baseTrueType, combinedMapper || mapper);
+ if (!root.isDistributive || !maybeTypeOfKind(checkType, 7897088)) {
+ var combinedMapper = void 0;
+ if (root.inferTypeParameters) {
+ var context = createInferenceContext(root.inferTypeParameters, undefined, 0);
+ inferTypes(context.inferences, checkType, extendsType, 16 | 32);
+ combinedMapper = combineTypeMappers(mapper, context);
+ }
+ if (checkType.flags & 1) {
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ }
+ var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
+ if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) {
+ return instantiateType(root.falseType, mapper);
+ }
+ if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) {
+ return instantiateType(root.trueType, combinedMapper || mapper);
+ }
}
var erasedCheckType = getActualTypeParameter(checkType);
- var trueType = instantiateType(baseTrueType, mapper);
- var falseType = instantiateType(baseFalseType, mapper);
- var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 ? 1 : 0;
- var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive;
- var cached = conditionalTypes.get(id);
- if (cached) {
- return cached;
- }
- var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper));
- conditionalTypes.set(id, result);
+ var result = createType(2097152);
+ result.root = root;
+ result.checkType = erasedCheckType;
+ result.extendsType = extendsType;
+ result.mapper = mapper;
+ result.aliasSymbol = root.aliasSymbol;
+ result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper);
return result;
}
- function isDistributiveConditionalType(type) {
- return !!((type.target || type).checkType.flags & 32768);
+ function getTrueTypeFromConditionalType(type) {
+ return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
+ }
+ function getFalseTypeFromConditionalType(type) {
+ return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -26303,7 +26485,28 @@ var ts;
function getTypeFromConditionalTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), undefined, undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node));
+ var checkType = getTypeFromTypeNode(node.checkType);
+ var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ var allOuterTypeParameters = getOuterTypeParameters(node, true);
+ var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
+ var root = {
+ node: node,
+ checkType: checkType,
+ extendsType: getTypeFromTypeNode(node.extendsType),
+ trueType: getTypeFromTypeNode(node.trueType),
+ falseType: getTypeFromTypeNode(node.falseType),
+ isDistributive: !!(checkType.flags & 32768),
+ inferTypeParameters: getInferTypeParameters(node),
+ outerTypeParameters: outerTypeParameters,
+ instantiations: undefined,
+ aliasSymbol: getAliasSymbolForTypeNode(node),
+ aliasTypeArguments: aliasTypeArguments
+ };
+ links.resolvedType = getConditionalType(root, undefined);
+ if (outerTypeParameters) {
+ root.instantiations = ts.createMap();
+ root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
+ }
}
return links.resolvedType;
}
@@ -26630,14 +26833,18 @@ var ts;
return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
}
function isInferenceContext(mapper) {
- return !!mapper.signature;
+ return !!mapper.typeParameters;
}
function cloneTypeMapper(mapper) {
return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) :
+ createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) :
mapper;
}
function combineTypeMappers(mapper1, mapper2) {
+ if (!mapper1)
+ return mapper2;
+ if (!mapper2)
+ return mapper1;
return function (t) { return instantiateType(mapper1(t), mapper2); };
}
function createReplacementMapper(source, target, baseMapper) {
@@ -26789,19 +26996,29 @@ var ts;
return result;
}
function getConditionalTypeInstantiation(type, mapper) {
- var target = type.target || type;
- var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper;
- if (isDistributiveConditionalType(target)) {
- var checkType_1 = target.checkType;
- var instantiatedType = combinedMapper(checkType_1);
- if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072) {
- return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); });
+ var root = type.root;
+ if (root.outerTypeParameters) {
+ var typeArguments = ts.map(root.outerTypeParameters, mapper);
+ var id = getTypeListId(typeArguments);
+ var result = root.instantiations.get(id);
+ if (!result) {
+ var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
+ result = instantiateConditionalType(root, newMapper);
+ root.instantiations.set(id, result);
+ }
+ return result;
+ }
+ return type;
+ }
+ function instantiateConditionalType(root, mapper) {
+ if (root.isDistributive) {
+ var checkType_1 = root.checkType;
+ var instantiatedType = mapper(checkType_1);
+ if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 | 16384)) {
+ return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); });
}
}
- return instantiateConditionalType(target, combinedMapper);
- }
- function instantiateConditionalType(type, mapper) {
- return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments);
+ return getConditionalType(root, mapper);
}
function instantiateType(type, mapper) {
if (type && mapper && mapper !== identityMapper) {
@@ -26839,7 +27056,7 @@ var ts;
return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
}
if (type.flags & 2097152) {
- return getConditionalTypeInstantiation(type, mapper);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (type.flags & 4194304) {
return mapper(type.typeParameter);
@@ -27414,11 +27631,11 @@ var ts;
}
}
if (flags & 2097152) {
- if (result = isRelatedTo(source.checkType, target.checkType, false)) {
- if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) {
- if (result &= isRelatedTo(source.trueType, target.trueType, false)) {
- if (result &= isRelatedTo(source.falseType, target.falseType, false)) {
- if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) {
+ if (source.root.isDistributive === target.root.isDistributive) {
+ if (result = isRelatedTo(source.checkType, target.checkType, false)) {
+ if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) {
+ if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) {
+ if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) {
return result;
}
}
@@ -27764,20 +27981,11 @@ var ts;
}
}
else if (source.flags & 2097152) {
- if (relation !== definitelyAssignableRelation) {
- var constraint = getConstraintOfDistributiveConditionalType(source);
- if (constraint) {
- if (result = isRelatedTo(constraint, target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
- }
- }
- }
if (target.flags & 2097152) {
if (isTypeIdenticalTo(source.checkType, target.checkType) &&
isTypeIdenticalTo(source.extendsType, target.extendsType)) {
- if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
- result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
+ if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
+ result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -27785,9 +27993,21 @@ var ts;
}
}
}
- else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
+ else if (relation !== definitelyAssignableRelation) {
+ var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
+ if (distributiveConstraint) {
+ if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ var defaultConstraint = getDefaultConstraintOfConditionalType(source);
+ if (defaultConstraint) {
+ if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
}
}
else {
@@ -28509,8 +28729,17 @@ var ts;
ts.Debug.assert(strictNullChecks);
return type.flags & 4096 ? type : getUnionType([type, undefinedType]);
}
+ function getGlobalNonNullableTypeInstantiation(type) {
+ if (!deferredGlobalNonNullableTypeAlias) {
+ deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288, undefined) || unknownSymbol;
+ }
+ if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
+ return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
+ }
+ return getTypeWithFacts(type, 524288);
+ }
function getNonNullableType(type) {
- return strictNullChecks ? getTypeWithFacts(type, 524288) : type;
+ return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
}
function isObjectTypeWithInferableIndex(type) {
return type.symbol && (type.symbol.flags & (4096 | 2048 | 512)) !== 0 &&
@@ -28603,6 +28832,10 @@ var ts;
}
var result = createSymbol(4 | 16777216, name);
result.type = undefinedType;
+ var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (associatedKeyType.flags & 32) {
+ result.nameType = associatedKeyType;
+ }
undefinedProperties.set(name, result);
return result;
}
@@ -28749,9 +28982,10 @@ var ts;
callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
}
}
- function createInferenceContext(signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo);
+ function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
+ var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(typeParameters, createInferenceInfo);
var context = mapper;
+ context.typeParameters = typeParameters;
context.signature = signature;
context.inferences = inferences;
context.flags = flags;
@@ -28858,7 +29092,7 @@ var ts;
var templateType = getTemplateTypeFromMappedType(target);
var inference = createInferenceInfo(typeParameter);
inferTypes([inference], sourceType, templateType);
- return getTypeFromInference(inference) || emptyObjectType;
+ return getTypeFromInference(inference);
}
function getUnmatchedProperty(source, target, requireOptionalProperties) {
var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
@@ -28876,18 +29110,26 @@ var ts;
function getTypeFromInference(inference) {
return inference.candidates ? getUnionType(inference.candidates, 2) :
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
- undefined;
+ emptyObjectType;
}
function inferTypes(inferences, originalSource, originalTarget, priority) {
if (priority === void 0) { priority = 0; }
var symbolStack;
var visited;
var contravariant = false;
+ var propagationType;
inferFromTypes(originalSource, originalTarget);
function inferFromTypes(source, target) {
if (!couldContainTypeVariables(target)) {
return;
}
+ if (source.flags & 1) {
+ var savePropagationType = propagationType;
+ propagationType = source;
+ inferFromTypes(target, target);
+ propagationType = savePropagationType;
+ return;
+ }
if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
var sourceTypes = source.aliasTypeArguments;
var targetTypes = target.aliasTypeArguments;
@@ -28937,14 +29179,15 @@ var ts;
inference.priority = priority;
}
if (priority === inference.priority) {
+ var candidate = propagationType || source;
if (contravariant) {
- inference.contraCandidates = ts.append(inference.contraCandidates, source);
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
}
else {
- inference.candidates = ts.append(inference.candidates, source);
+ inference.candidates = ts.append(inference.candidates, candidate);
}
}
- if (!(priority & 4) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
}
}
@@ -28983,8 +29226,8 @@ var ts;
else if (source.flags & 2097152 && target.flags & 2097152) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(source.trueType, target.trueType);
- inferFromTypes(source.falseType, target.falseType);
+ inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
+ inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
}
else if (target.flags & 393216) {
var targetTypes = target.types;
@@ -29015,7 +29258,7 @@ var ts;
}
}
else {
- if (!(priority && 8 && source.flags & (262144 | 7897088))) {
+ if (!(priority & 16 && source.flags & (262144 | 7897088))) {
source = getApparentType(source);
}
if (source.flags & (65536 | 262144)) {
@@ -29042,7 +29285,7 @@ var ts;
}
}
function inferFromContravariantTypes(source, target) {
- if (strictFunctionTypes || priority & 16) {
+ if (strictFunctionTypes || priority & 32) {
contravariant = !contravariant;
inferFromTypes(source, target);
contravariant = !contravariant;
@@ -29083,7 +29326,10 @@ var ts;
return;
}
if (constraintType.flags & 32768) {
+ var savePriority = priority;
+ priority |= 4;
inferFromTypes(getIndexType(source), constraintType);
+ priority = savePriority;
inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target));
return;
}
@@ -29186,39 +29432,44 @@ var ts;
var inference = context.inferences[index];
var inferredType = inference.inferredType;
if (!inferredType) {
- if (inference.candidates) {
- var candidates = widenObjectLiteralCandidates(inference.candidates);
- var signature = context.signature;
- var widenLiteralTypes = inference.topLevel &&
- !hasPrimitiveConstraint(inference.typeParameter) &&
- (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
- var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
- var unwidenedType = context.flags & 1 || inference.priority & 4 ?
- getUnionType(baseCandidates, 2) :
- getCommonSupertype(baseCandidates);
- inferredType = getWidenedType(unwidenedType);
- if (inferredType.flags & 16384 && inference.contraCandidates) {
+ var signature = context.signature;
+ if (signature) {
+ if (inference.candidates) {
+ var candidates = widenObjectLiteralCandidates(inference.candidates);
+ var widenLiteralTypes = inference.topLevel &&
+ !hasPrimitiveConstraint(inference.typeParameter) &&
+ (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
+ var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
+ var unwidenedType = context.flags & 1 || inference.priority & 12 ?
+ getUnionType(baseCandidates, 2) :
+ getCommonSupertype(baseCandidates);
+ inferredType = getWidenedType(unwidenedType);
+ if (inferredType.flags & 16384 && inference.contraCandidates) {
+ inferredType = getCommonSubtype(inference.contraCandidates);
+ }
+ }
+ else if (inference.contraCandidates) {
inferredType = getCommonSubtype(inference.contraCandidates);
}
- }
- else if (inference.contraCandidates) {
- inferredType = getCommonSubtype(inference.contraCandidates);
- }
- else if (context.flags & 2) {
- inferredType = silentNeverType;
- }
- else {
- var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
- if (defaultType) {
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ else if (context.flags & 2) {
+ inferredType = silentNeverType;
}
else {
- inferredType = getDefaultTypeArgumentType(!!(context.flags & 4));
+ var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
+ if (defaultType) {
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ }
+ else {
+ inferredType = getDefaultTypeArgumentType(!!(context.flags & 4));
+ }
}
}
+ else {
+ inferredType = getTypeFromInference(inference);
+ }
inferredType = getWidenedUniqueESSymbolType(inferredType);
inference.inferredType = inferredType;
- var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]);
+ var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
var instantiatedConstraint = instantiateType(constraint, context);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
@@ -29252,7 +29503,7 @@ var ts;
function getFlowCacheKey(node) {
if (node.kind === 71) {
var symbol = getResolvedSymbol(node);
- return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
+ return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
}
if (node.kind === 99) {
return "0";
@@ -29461,8 +29712,8 @@ var ts;
}
if (flags & 65536) {
return isFunctionObjectType(type) ?
- strictNullChecks ? 6164448 : 8376288 :
- strictNullChecks ? 6166480 : 8378320;
+ strictNullChecks ? 1970144 : 4181984 :
+ strictNullChecks ? 1972176 : 4184016;
}
if (flags & (2048 | 4096)) {
return 2457472;
@@ -29474,7 +29725,7 @@ var ts;
return strictNullChecks ? 1981320 : 4193160;
}
if (flags & 134217728) {
- return strictNullChecks ? 6166480 : 8378320;
+ return strictNullChecks ? 1972176 : 4184016;
}
if (flags & 7897088) {
return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType);
@@ -29482,7 +29733,7 @@ var ts;
if (flags & 393216) {
return getTypeFactsOfTypes(type.types);
}
- return 8388607;
+ return 4194303;
}
function getTypeWithFacts(type, include) {
return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
@@ -29672,6 +29923,9 @@ var ts;
return f(type) ? type : neverType;
}
function mapType(type, mapper, noReductions) {
+ if (type.flags & 16384) {
+ return type;
+ }
if (!(type.flags & 131072)) {
return mapper(type);
}
@@ -30395,20 +30649,19 @@ var ts;
!(getFalsyFlags(checkExpression(declaration.initializer)) & 4096);
return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType;
}
- function isApparentTypePosition(node) {
+ function isConstraintPosition(node) {
var parent = node.parent;
return parent.kind === 183 ||
parent.kind === 185 && parent.expression === node ||
parent.kind === 184 && parent.expression === node ||
- parent.kind === 207 ||
parent.kind === 180 && parent.name === node && !!parent.initializer;
}
function typeHasNullableConstraint(type) {
return type.flags & 7372800 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288);
}
- function getApparentTypeForLocation(type, node) {
- if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) {
- return mapType(getWidenedType(type), getApparentType);
+ function getConstraintForLocation(type, node) {
+ if (isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
+ return mapType(getWidenedType(type), getBaseConstraintOrType);
}
return type;
}
@@ -30471,7 +30724,7 @@ var ts;
checkCollisionWithCapturedThisVariable(node, node);
checkCollisionWithCapturedNewTargetVariable(node, node);
checkNestedBlockScopedBinding(node, symbol);
- var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node);
+ var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
var assignmentKind = ts.getAssignmentTargetKind(node);
if (assignmentKind) {
if (!(localOrExportSymbol.flags & 3)) {
@@ -31106,7 +31359,7 @@ var ts;
}
function getContextualTypeForChildJsxExpression(node) {
var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined;
}
function getContextualTypeForJsxExpression(node) {
@@ -31232,20 +31485,14 @@ var ts;
return anyType;
}
var isJs = ts.isInJavaScriptFile(node);
- return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes);
+ return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); });
}
- function getJsxSignaturesParameterTypes(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, false);
- }
- function getJsxSignaturesParameterTypesJs(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, true);
- }
- function getJsxSignaturesParameterTypesInternal(valueType, isJs) {
+ function getJsxSignaturesParameterTypes(valueType, isJs, context) {
if (valueType.flags & 2) {
return anyType;
}
else if (valueType.flags & 32) {
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = valueType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -31268,21 +31515,21 @@ var ts;
return unknownType;
}
}
- return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0);
+ return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0);
}
- function getJsxPropsTypeFromCallSignature(sig) {
+ function getJsxPropsTypeFromCallSignature(sig, context) {
var propsType = getTypeOfFirstParameterOfSignature(sig);
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
propsType = intersectTypes(intrinsicAttribs, propsType);
}
return propsType;
}
- function getJsxPropsTypeFromClassType(hostClassType, isJs) {
+ function getJsxPropsTypeFromClassType(hostClassType, isJs, context) {
if (isTypeAny(hostClassType)) {
return hostClassType;
}
- var propsName = getJsxElementPropertiesName();
+ var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context));
if (propsName === undefined) {
return anyType;
}
@@ -31299,14 +31546,14 @@ var ts;
}
else {
var apparentAttributesType = attributesType;
- var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes);
+ var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
if (intrinsicClassAttribs !== unknownType) {
var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
apparentAttributesType = intersectTypes(typeParams
? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs))
: intrinsicClassAttribs, apparentAttributesType);
}
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
}
@@ -31314,18 +31561,12 @@ var ts;
}
}
}
- function getJsxPropsTypeFromConstructSignatureJs(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, true);
- }
- function getJsxPropsTypeFromConstructSignature(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, false);
- }
- function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) {
+ function getJsxPropsTypeFromConstructSignature(sig, isJs, context) {
var hostClassType = getReturnTypeOfSignature(sig);
if (hostClassType) {
- return getJsxPropsTypeFromClassType(hostClassType, isJs);
+ return getJsxPropsTypeFromClassType(hostClassType, isJs, context);
}
- return getJsxPropsTypeFromCallSignature(sig);
+ return getJsxPropsTypeFromCallSignature(sig, context);
}
function getContextualCallSignature(type, node) {
var signatures = getSignaturesOfType(type, 0);
@@ -31560,9 +31801,13 @@ var ts;
}
typeFlags |= type.flags;
var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined;
- var prop = nameType && isTypeUsableAsLateBoundName(nameType)
+ var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType);
+ var prop = hasLateBoundName
? createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 1024)
: createSymbol(4 | member.flags, literalName || member.escapedName);
+ if (hasLateBoundName) {
+ prop.nameType = nameType;
+ }
if (inDestructuringPattern) {
var isOptional = (memberDecl.kind === 268 && hasDefaultValue(memberDecl.initializer)) ||
(memberDecl.kind === 269 && memberDecl.objectAssignmentInitializer);
@@ -31675,7 +31920,7 @@ var ts;
}
function checkJsxSelfClosingElement(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode);
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxElement(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode);
@@ -31685,14 +31930,16 @@ var ts;
else {
checkExpression(node.closingElement.tagName);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxFragment(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode);
- if (compilerOptions.jsx === 2 && compilerOptions.jsxFactory) {
- error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory);
+ if (compilerOptions.jsx === 2 && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
+ error(node, compilerOptions.jsxFactory
+ ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
+ : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function isUnhyphenatedJsxName(name) {
return !ts.stringContains(name, "-");
@@ -31720,7 +31967,7 @@ var ts;
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
var attributeDecl = _a[_i];
var member = attributeDecl.symbol;
@@ -31807,20 +32054,19 @@ var ts;
function checkJsxAttributes(node, checkMode) {
return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
}
- function getJsxType(name) {
- var jsxType = jsxTypes.get(name);
- if (jsxType === undefined) {
- jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType);
- }
- return jsxType;
+ function getJsxType(name, location) {
+ var namespace = getJsxNamespaceAt(location);
+ var exports = namespace && getExportsOfSymbol(namespace);
+ var typeSymbol = exports && getSymbol(exports, name, 793064);
+ return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType;
}
function getIntrinsicTagSymbol(node) {
var links = getNodeLinks(node);
if (!links.resolvedSymbol) {
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
if (intrinsicElementsType !== unknownType) {
if (!ts.isIdentifier(node.tagName))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
if (intrinsicProp) {
links.jsxFlags |= 1;
@@ -31861,7 +32107,7 @@ var ts;
var signature = signatures_3[_i];
if (signature.typeParameters) {
var isJavascript = ts.isInJavaScriptFile(node);
- var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0);
+ var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 4 : 0);
var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext);
instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript));
}
@@ -31871,8 +32117,18 @@ var ts;
}
return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2);
}
- function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) {
- var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined);
+ function getJsxNamespaceAt(location) {
+ var namespaceName = getJsxNamespace(location);
+ var resolvedNamespace = resolveName(location, namespaceName, 1920, undefined, namespaceName, false);
+ if (resolvedNamespace) {
+ var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920);
+ if (candidate) {
+ return candidate;
+ }
+ }
+ return getGlobalSymbol(JsxNames.JSX, 1920, undefined);
+ }
+ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064);
var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
@@ -31889,19 +32145,11 @@ var ts;
}
return undefined;
}
- function getJsxElementPropertiesName() {
- if (!_hasComputedJsxElementPropertiesName) {
- _hasComputedJsxElementPropertiesName = true;
- _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer);
- }
- return _jsxElementPropertiesName;
+ function getJsxElementPropertiesName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
}
- function getJsxElementChildrenPropertyName() {
- if (!_hasComputedJsxElementChildrenPropertyName) {
- _hasComputedJsxElementChildrenPropertyName = true;
- _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer);
- }
- return _jsxElementChildrenPropertyName;
+ function getJsxElementChildrenPropertyName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
function getApparentTypeOfJsxPropsType(propsType) {
if (!propsType) {
@@ -31920,7 +32168,7 @@ var ts;
function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
ts.Debug.assert(!(elementType.flags & 131072));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined);
if (callSignature !== unknownSignature) {
@@ -31928,7 +32176,7 @@ var ts;
var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0]));
paramType = getApparentTypeOfJsxPropsType(paramType);
if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
paramType = intersectTypes(intrinsicAttributes, paramType);
}
@@ -31942,7 +32190,7 @@ var ts;
function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
ts.Debug.assert(!(elementType.flags & 131072));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
var candidatesOutArray = [];
getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray);
@@ -31973,7 +32221,7 @@ var ts;
if (!result) {
result = allMatchingAttributesType;
}
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
result = intersectTypes(intrinsicAttributes, result);
}
@@ -31993,7 +32241,7 @@ var ts;
return anyType;
}
else if (elementType.flags & 32) {
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = elementType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -32018,7 +32266,7 @@ var ts;
if (elementClassType) {
checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
}
- return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement));
+ return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement);
}
function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
@@ -32038,7 +32286,7 @@ var ts;
return links.resolvedJsxElementAttributesType;
}
function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) {
- return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType());
+ return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node));
}
function getAllAttributesTypeFromJsxOpeningLikeElement(node) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
@@ -32061,36 +32309,30 @@ var ts;
var prop = getPropertyOfType(attributesType, attrib.name.escapedText);
return prop || unknownSymbol;
}
- function getJsxGlobalElementClassType() {
- if (!deferredJsxElementClassType) {
- deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass);
- }
- return deferredJsxElementClassType;
+ function getJsxElementClassTypeAt(location) {
+ var type = getJsxType(JsxNames.ElementClass, location);
+ if (type === unknownType)
+ return undefined;
+ return type;
}
- function getJsxGlobalElementType() {
- if (!deferredJsxElementType) {
- deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element);
- }
- return deferredJsxElementType;
+ function getJsxElementTypeAt(location) {
+ return getJsxType(JsxNames.Element, location);
}
- function getJsxGlobalStatelessElementType() {
- if (!deferredJsxStatelessElementType) {
- var jsxElementType = getJsxGlobalElementType();
- if (jsxElementType) {
- deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]);
- }
+ function getJsxStatelessElementTypeAt(location) {
+ var jsxElementType = getJsxElementTypeAt(location);
+ if (jsxElementType) {
+ return getUnionType([jsxElementType, nullType]);
}
- return deferredJsxStatelessElementType;
}
- function getJsxIntrinsicTagNames() {
- var intrinsics = getJsxType(JsxNames.IntrinsicElements);
+ function getJsxIntrinsicTagNamesAt(location) {
+ var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
}
function checkJsxPreconditions(errorNode) {
if ((compilerOptions.jsx || 0) === 0) {
error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
}
- if (getJsxGlobalElementType() === undefined) {
+ if (getJsxElementTypeAt(errorNode) === undefined) {
if (noImplicitAny) {
error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
}
@@ -32103,7 +32345,7 @@ var ts;
}
checkJsxPreconditions(node);
var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined;
- var reactNamespace = getJsxNamespace();
+ var reactNamespace = getJsxNamespace(node);
var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
var reactSym = resolveName(reactLocation, reactNamespace, 107455, reactRefErr, reactNamespace, true);
if (reactSym) {
@@ -32145,7 +32387,7 @@ var ts;
getCustomJsxElementAttributesType(openingLikeElement, false);
var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode);
if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || getPropertiesOfType(sourceAttributesType).length > 0)) {
- error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName()));
+ error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement))));
}
else {
var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement);
@@ -32315,7 +32557,7 @@ var ts;
return unknownType;
}
}
- propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node);
+ propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
}
if (node.kind !== 183 ||
assignmentKind === 1 ||
@@ -32425,6 +32667,10 @@ var ts;
});
return result && ts.symbolName(result);
}
+ function getSuggestionForNonexistentModule(name, targetModule) {
+ var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475);
+ return suggestion && ts.symbolName(suggestion);
+ }
function getSpellingSuggestionForName(name, symbols, meaning) {
var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
var bestDistance = Math.floor(name.length * 0.4) + 1;
@@ -32765,12 +33011,12 @@ var ts;
return undefined;
}
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
- var context = createInferenceContext(signature, 1, compareTypes);
+ var context = createInferenceContext(signature.typeParameters, signature, 1, compareTypes);
forEachMatchingParameterType(contextualSignature, signature, function (source, target) {
inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target);
});
if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4);
+ inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8);
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration));
}
@@ -32799,7 +33045,7 @@ var ts;
getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) :
instantiatedType;
var inferenceTargetType = getReturnTypeOfSignature(signature);
- inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4);
+ inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8);
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -33210,7 +33456,7 @@ var ts;
}
var candidate = void 0;
var inferenceContext = originalCandidate.typeParameters ?
- createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) :
+ createInferenceContext(originalCandidate.typeParameters, originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) :
undefined;
while (true) {
candidate = originalCandidate;
@@ -33665,7 +33911,7 @@ var ts;
return false;
}
if (!ts.isIdentifier(node.expression))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined, true);
if (!resolvedRequire) {
return true;
@@ -36512,7 +36758,7 @@ var ts;
var symbol = getSymbolOfNode(node);
if (symbol.flags & 1) {
if (!ts.isIdentifier(node.name))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined, false);
if (localDeclarationSymbol &&
localDeclarationSymbol !== symbol &&
@@ -37445,7 +37691,7 @@ var ts;
var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
if (prop && baseProp) {
- var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); };
+ var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); };
if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, undefined, rootChain)) {
issuedMemberError = true;
}
@@ -37997,7 +38243,10 @@ var ts;
}
function checkExternalImportOrExportDeclaration(node) {
var moduleName = ts.getExternalModuleName(node);
- if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) {
+ if (ts.nodeIsMissing(moduleName)) {
+ return false;
+ }
+ if (!ts.isStringLiteral(moduleName)) {
error(moduleName, ts.Diagnostics.String_literal_expected);
return false;
}
@@ -38008,7 +38257,7 @@ var ts;
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
return false;
}
- if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) {
+ if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
if (!isTopLevelInExternalModuleAugmentation(node)) {
error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
return false;
@@ -39382,7 +39631,7 @@ var ts;
return !!(symbol && ts.getCheckFlags(symbol) & 1024);
},
writeLiteralConstValue: writeLiteralConstValue,
- getJsxFactoryEntity: function () { return _jsxFactoryEntity; }
+ getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }
};
function getTypeReferenceDirectivesForEntityName(node) {
if (!fileToDirective) {
@@ -40872,9 +41121,15 @@ var ts;
: node;
}
ts.updateQualifiedName = updateQualifiedName;
+ function parenthesizeForComputedName(expression) {
+ return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26) ||
+ expression.kind === 296 ?
+ createParen(expression) :
+ expression;
+ }
function createComputedPropertyName(expression) {
var node = createSynthesizedNode(146);
- node.expression = expression;
+ node.expression = parenthesizeForComputedName(expression);
return node;
}
ts.createComputedPropertyName = createComputedPropertyName;
@@ -42657,7 +42912,7 @@ var ts;
var node = createSynthesizedNode(268);
node.name = asName(name);
node.questionToken = undefined;
- node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
+ node.initializer = ts.parenthesizeExpressionForList(initializer);
return node;
}
ts.createPropertyAssignment = createPropertyAssignment;
@@ -42765,6 +43020,12 @@ var ts;
updated.imports = node.imports;
if (node.moduleAugmentations !== undefined)
updated.moduleAugmentations = node.moduleAugmentations;
+ if (node.pragmas !== undefined)
+ updated.pragmas = node.pragmas;
+ if (node.localJsxFactory !== undefined)
+ updated.localJsxFactory = node.localJsxFactory;
+ if (node.localJsxNamespace !== undefined)
+ updated.localJsxNamespace = node.localJsxNamespace;
return updateNode(updated, node);
}
return node;
@@ -45186,7 +45447,7 @@ var ts;
var uniqueExports = ts.createMap();
var exportedNames;
var hasExportDefault = false;
- var exportEquals = undefined;
+ var exportEquals;
var hasExportStarsToExportValues = false;
var hasImportStarOrImportDefault = false;
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
@@ -46174,7 +46435,7 @@ var ts;
ts.setEmitFlags(propertyName, 1536 | 48);
var localName = ts.getMutableClone(name);
ts.setEmitFlags(localName, 1536);
- return ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)));
+ return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536));
}
function getInitializedProperties(node, isStatic) {
return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty);
@@ -48373,14 +48634,14 @@ var ts;
objectProperties = ts.createAssignHelper(context, segments);
}
}
- var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
return element;
}
function visitJsxOpeningFragment(node, children, isChild, location) {
- var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
@@ -49350,11 +49611,11 @@ var ts;
function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
initializer = ts.visitNode(initializer, visitor, ts.isExpression);
var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
- ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer))), parameter))
- ]), parameter), 1 | 32 | 384));
+ ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer) | 1536)), parameter), 1536))
+ ]), parameter), 1 | 32 | 384 | 1536));
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
- ts.setEmitFlags(statement, 384 | 32 | 1048576);
+ ts.setEmitFlags(statement, 384 | 32 | 1048576 | 1536);
statements.push(statement);
}
function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
@@ -53235,12 +53496,12 @@ var ts;
var importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
- text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}"
+ text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
var importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
- text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}"
+ text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
};
})(ts || (ts = {}));
var ts;
@@ -55220,8 +55481,8 @@ var ts;
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = ts.createMap();
}
- for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) {
- var directive = typeReferenceDirectives_1[_i];
+ for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
+ var directive = typeReferenceDirectives_2[_i];
if (!usedTypeDirectiveReferences.has(directive)) {
usedTypeDirectiveReferences.set(directive, directive);
}
@@ -55499,7 +55760,12 @@ var ts;
"?");
}
write(": ");
- emitType(node.type);
+ if (node.type) {
+ emitType(node.type);
+ }
+ else {
+ write("any");
+ }
write(";");
writeLine();
decreaseIndent();
@@ -57484,7 +57750,7 @@ var ts;
else {
emitTypeAnnotation(node.type);
}
- emitInitializer(node.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);
}
function emitDecorator(decorator) {
writePunctuation("@");
@@ -57503,8 +57769,9 @@ var ts;
emitModifiers(node, node.modifiers);
emit(node.name);
emitIfPresent(node.questionToken);
+ emitIfPresent(node.exclamationToken);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
writeSemicolon();
}
function emitMethodSignature(node) {
@@ -57743,7 +58010,7 @@ var ts;
writeSpace();
}
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
function emitArrayLiteralExpression(node) {
var elements = node.elements;
@@ -57777,7 +58044,10 @@ var ts;
emitExpression(node.expression);
increaseIndentIf(indentBeforeDot);
var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression);
- writePunctuation(shouldEmitDotDot ? ".." : ".");
+ if (shouldEmitDotDot) {
+ writePunctuation(".");
+ }
+ emitTokenWithComment(23, node.expression.end, writePunctuation, node);
increaseIndentIf(indentAfterDot);
emit(node.name);
decreaseIndentIf(indentBeforeDot, indentAfterDot);
@@ -57798,9 +58068,9 @@ var ts;
}
function emitElementAccessExpression(node) {
emitExpression(node.expression);
- writePunctuation("[");
+ var openPos = emitTokenWithComment(21, node.expression.end, writePunctuation, node);
emitExpression(node.argumentExpression);
- writePunctuation("]");
+ emitTokenWithComment(22, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node);
}
function emitCallExpression(node) {
emitExpression(node.expression);
@@ -57808,7 +58078,7 @@ var ts;
emitExpressionList(node, node.arguments, 1296);
}
function emitNewExpression(node) {
- writeKeyword("new");
+ emitTokenWithComment(94, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
emitTypeArguments(node, node.typeArguments);
@@ -57826,9 +58096,9 @@ var ts;
emitExpression(node.expression);
}
function emitParenthesizedExpression(node) {
- writePunctuation("(");
+ var openParenPos = emitTokenWithComment(19, node.pos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
}
function emitFunctionExpression(node) {
emitFunctionDeclarationOrExpression(node);
@@ -57846,22 +58116,22 @@ var ts;
emit(node.equalsGreaterThanToken);
}
function emitDeleteExpression(node) {
- writeKeyword("delete");
+ emitTokenWithComment(80, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitTypeOfExpression(node) {
- writeKeyword("typeof");
+ emitTokenWithComment(103, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitVoidExpression(node) {
- writeKeyword("void");
+ emitTokenWithComment(105, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitAwaitExpression(node) {
- writeKeyword("await");
+ emitTokenWithComment(121, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
@@ -57917,7 +58187,7 @@ var ts;
emitList(node, node.templateSpans, 131072);
}
function emitYieldExpression(node) {
- writeKeyword("yield");
+ emitTokenWithComment(116, node.pos, writeKeyword, node);
emit(node.asteriskToken);
emitExpressionWithLeadingSpace(node.expression);
}
@@ -57955,16 +58225,13 @@ var ts;
emit(node.literal);
}
function emitBlock(node) {
- writeToken(17, node.pos, writePunctuation, node);
emitBlockStatements(node, !node.multiLine && isEmptyBlock(node));
- increaseIndent();
- emitLeadingCommentsOfPosition(node.statements.end);
- decreaseIndent();
- writeToken(18, node.statements.end, writePunctuation, node);
}
function emitBlockStatements(node, forceSingleLine) {
+ emitTokenWithComment(17, node.pos, writePunctuation, node);
var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65;
emitList(node, node.statements, format);
+ emitTokenWithComment(18, node.statements.end, writePunctuation, node, !!(format & 1));
}
function emitVariableStatement(node) {
emitModifiers(node, node.modifiers);
@@ -57979,15 +58246,15 @@ var ts;
writeSemicolon();
}
function emitIfStatement(node) {
- var openParenPos = writeToken(90, node.pos, writeKeyword, node);
+ var openParenPos = emitTokenWithComment(90, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19, openParenPos, writePunctuation, node);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20, node.expression.end, writePunctuation, node);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.thenStatement);
if (node.elseStatement) {
writeLineOrSpace(node);
- writeToken(82, node.thenStatement.end, writeKeyword, node);
+ emitTokenWithComment(82, node.thenStatement.end, writeKeyword, node);
if (node.elseStatement.kind === 215) {
writeSpace();
emit(node.elseStatement);
@@ -57997,8 +58264,15 @@ var ts;
}
}
}
+ function emitWhileClause(node, startPos) {
+ var openParenPos = emitTokenWithComment(106, startPos, writeKeyword, node);
+ writeSpace();
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
+ emitExpression(node.expression);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
+ }
function emitDoStatement(node) {
- writeKeyword("do");
+ emitTokenWithComment(81, node.pos, writeKeyword, node);
emitEmbeddedStatement(node, node.statement);
if (ts.isBlock(node.statement)) {
writeSpace();
@@ -58006,55 +58280,48 @@ var ts;
else {
writeLineOrSpace(node);
}
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(");");
+ emitWhileClause(node, node.statement.end);
+ writePunctuation(";");
}
function emitWhileStatement(node) {
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(")");
+ emitWhileClause(node, node.pos);
emitEmbeddedStatement(node, node.statement);
}
function emitForStatement(node) {
- var openParenPos = writeToken(88, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19, openParenPos, writePunctuation, node);
+ var pos = emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
- writeSemicolon();
+ pos = emitTokenWithComment(25, node.initializer ? node.initializer.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.condition);
- writeSemicolon();
+ pos = emitTokenWithComment(25, node.condition ? node.condition.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.incrementor);
- writePunctuation(")");
+ emitTokenWithComment(20, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForInStatement(node) {
- var openParenPos = writeToken(88, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19, openParenPos, writePunctuation);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("in");
+ emitTokenWithComment(92, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20, node.expression.end, writePunctuation);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForOfStatement(node) {
- var openParenPos = writeToken(88, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node);
writeSpace();
emitWithTrailingSpace(node.awaitModifier);
- writeToken(19, openParenPos, writePunctuation);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("of");
+ emitTokenWithComment(144, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20, node.expression.end, writePunctuation);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForBinding(node) {
@@ -58068,22 +58335,34 @@ var ts;
}
}
function emitContinueStatement(node) {
- writeToken(77, node.pos, writeKeyword);
+ emitTokenWithComment(77, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
function emitBreakStatement(node) {
- writeToken(72, node.pos, writeKeyword);
+ emitTokenWithComment(72, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
- function emitTokenWithComment(token, pos, writer, contextNode) {
+ function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
var node = contextNode && ts.getParseTreeNode(contextNode);
- if (node && node.kind === contextNode.kind) {
+ var isSimilarNode = node && node.kind === contextNode.kind;
+ var startPos = pos;
+ if (isSimilarNode) {
pos = ts.skipTrivia(currentSourceFile.text, pos);
}
- pos = writeToken(token, pos, writer, contextNode);
- if (node && node.kind === contextNode.kind) {
+ if (emitLeadingCommentsOfPosition && isSimilarNode) {
+ var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
+ if (needsIndent) {
+ increaseIndent();
+ }
+ emitLeadingCommentsOfPosition(startPos);
+ if (needsIndent) {
+ decreaseIndent();
+ }
+ }
+ pos = writeTokenText(token, writer, pos);
+ if (emitTrailingCommentsOfPosition && isSimilarNode) {
emitTrailingCommentsOfPosition(pos, true);
}
return pos;
@@ -58094,35 +58373,35 @@ var ts;
writeSemicolon();
}
function emitWithStatement(node) {
- writeKeyword("with");
+ var openParenPos = emitTokenWithComment(107, node.pos, writeKeyword, node);
writeSpace();
- writePunctuation("(");
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitSwitchStatement(node) {
- var openParenPos = writeToken(98, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(98, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19, openParenPos, writePunctuation);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20, node.expression.end, writePunctuation);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
writeSpace();
emit(node.caseBlock);
}
function emitLabeledStatement(node) {
emit(node.label);
- writePunctuation(":");
+ emitTokenWithComment(56, node.label.end, writePunctuation, node);
writeSpace();
emit(node.statement);
}
function emitThrowStatement(node) {
- writeKeyword("throw");
+ emitTokenWithComment(100, node.pos, writeKeyword, node);
emitExpressionWithLeadingSpace(node.expression);
writeSemicolon();
}
function emitTryStatement(node) {
- writeKeyword("try");
+ emitTokenWithComment(102, node.pos, writeKeyword, node);
writeSpace();
emit(node.tryBlock);
if (node.catchClause) {
@@ -58131,7 +58410,7 @@ var ts;
}
if (node.finallyBlock) {
writeLineOrSpace(node);
- writeKeyword("finally");
+ emitTokenWithComment(87, (node.catchClause || node.tryBlock).end, writeKeyword, node);
writeSpace();
emit(node.finallyBlock);
}
@@ -58143,7 +58422,7 @@ var ts;
function emitVariableDeclaration(node) {
emit(node.name);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
}
function emitVariableDeclarationList(node) {
writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var");
@@ -58337,23 +58616,21 @@ var ts;
}
function emitModuleBlock(node) {
pushNameGenerationScope(node);
- writePunctuation("{");
emitBlockStatements(node, isEmptyBlock(node));
- writePunctuation("}");
popNameGenerationScope(node);
}
function emitCaseBlock(node) {
- writeToken(17, node.pos, writePunctuation);
+ emitTokenWithComment(17, node.pos, writePunctuation, node);
emitList(node, node.clauses, 65);
- writeToken(18, node.clauses.end, writePunctuation);
+ emitTokenWithComment(18, node.clauses.end, writePunctuation, node, true);
}
function emitImportEqualsDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSpace();
- writePunctuation("=");
+ emitTokenWithComment(58, node.name.end, writePunctuation, node);
writeSpace();
emitModuleReference(node.moduleReference);
writeSemicolon();
@@ -58368,12 +58645,12 @@ var ts;
}
function emitImportDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
if (node.importClause) {
emit(node.importClause);
writeSpace();
- writeKeyword("from");
+ emitTokenWithComment(142, node.importClause.end, writeKeyword, node);
writeSpace();
}
emitExpression(node.moduleSpecifier);
@@ -58382,15 +58659,15 @@ var ts;
function emitImportClause(node) {
emit(node.name);
if (node.name && node.namedBindings) {
- writePunctuation(",");
+ emitTokenWithComment(26, node.name.end, writePunctuation, node);
writeSpace();
}
emit(node.namedBindings);
}
function emitNamespaceImport(node) {
- writePunctuation("*");
+ var asPos = emitTokenWithComment(39, node.pos, writePunctuation, node);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118, asPos, writeKeyword, node);
writeSpace();
emit(node.name);
}
@@ -58401,41 +58678,42 @@ var ts;
emitImportOrExportSpecifier(node);
}
function emitExportAssignment(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node);
writeSpace();
if (node.isExportEquals) {
- writeOperator("=");
+ emitTokenWithComment(58, nextPos, writeOperator, node);
}
else {
- writeKeyword("default");
+ emitTokenWithComment(79, nextPos, writeKeyword, node);
}
writeSpace();
emitExpression(node.expression);
writeSemicolon();
}
function emitExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node);
writeSpace();
if (node.exportClause) {
emit(node.exportClause);
}
else {
- writePunctuation("*");
+ nextPos = emitTokenWithComment(39, nextPos, writePunctuation, node);
}
if (node.moduleSpecifier) {
writeSpace();
- writeKeyword("from");
+ var fromPos = node.exportClause ? node.exportClause.end : nextPos;
+ emitTokenWithComment(142, fromPos, writeKeyword, node);
writeSpace();
emitExpression(node.moduleSpecifier);
}
writeSemicolon();
}
function emitNamespaceExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node);
writeSpace();
- writeKeyword("as");
+ nextPos = emitTokenWithComment(118, nextPos, writeKeyword, node);
writeSpace();
- writeKeyword("namespace");
+ nextPos = emitTokenWithComment(130, nextPos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSemicolon();
@@ -58455,7 +58733,7 @@ var ts;
if (node.propertyName) {
emit(node.propertyName);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118, node.propertyName.end, writeKeyword, node);
writeSpace();
}
emit(node.name);
@@ -58536,30 +58814,29 @@ var ts;
}
}
function emitCaseClause(node) {
- writeKeyword("case");
+ emitTokenWithComment(73, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
}
function emitDefaultClause(node) {
- writeKeyword("default");
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ var pos = emitTokenWithComment(79, node.pos, writeKeyword, node);
+ emitCaseOrDefaultClauseRest(node, node.statements, pos);
}
- function emitCaseOrDefaultClauseStatements(parentNode, statements) {
+ function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
var emitAsSingleStatement = statements.length === 1 &&
(ts.nodeIsSynthesized(parentNode) ||
ts.nodeIsSynthesized(statements[0]) ||
ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
- if (statements.length > 0) {
- emitTrailingCommentsOfPosition(statements.pos);
- }
var format = 81985;
if (emitAsSingleStatement) {
+ writeToken(56, colonPos, writePunctuation, parentNode);
writeSpace();
format &= ~(1 | 64);
}
+ else {
+ emitTokenWithComment(56, colonPos, writePunctuation, parentNode);
+ }
emitList(parentNode, statements, format);
}
function emitHeritageClause(node) {
@@ -58569,12 +58846,12 @@ var ts;
emitList(node, node.types, 272);
}
function emitCatchClause(node) {
- var openParenPos = writeToken(74, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(74, node.pos, writeKeyword, node);
writeSpace();
if (node.variableDeclaration) {
- writeToken(19, openParenPos, writePunctuation);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emit(node.variableDeclaration);
- writeToken(20, node.variableDeclaration.end, writePunctuation);
+ emitTokenWithComment(20, node.variableDeclaration.end, writePunctuation, node);
writeSpace();
}
emit(node.block);
@@ -58607,7 +58884,7 @@ var ts;
}
function emitEnumMember(node) {
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
function emitSourceFile(node) {
writeLine();
@@ -58709,10 +58986,10 @@ var ts;
emit(node);
}
}
- function emitInitializer(node) {
+ function emitInitializer(node, equalCommentStartPos, container) {
if (node) {
writeSpace();
- writeOperator("=");
+ emitTokenWithComment(58, equalCommentStartPos, writeOperator, container);
writeSpace();
emitExpression(node);
}
@@ -58837,6 +59114,9 @@ var ts;
}
if (format & 7680) {
writePunctuation(getOpeningBracket(format));
+ if (isEmpty) {
+ emitTrailingCommentsOfPosition(children.pos, true);
+ }
}
if (onBeforeEmitNodeArray) {
onBeforeEmitNodeArray(children);
@@ -58920,6 +59200,9 @@ var ts;
onAfterEmitNodeArray(children);
}
if (format & 7680) {
+ if (isEmpty) {
+ emitLeadingCommentsOfPosition(children.end);
+ }
writePunctuation(getClosingBracket(format));
}
}
@@ -59829,8 +60112,7 @@ var ts;
}
ts.formatDiagnostics = formatDiagnostics;
function formatDiagnostic(diagnostic, host) {
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
+ var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
@@ -59854,8 +60136,9 @@ var ts;
var ellipsis = "...";
function getCategoryFormat(category) {
switch (category) {
- case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
+ case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
+ case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
}
}
@@ -59885,8 +60168,8 @@ var ts;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
- context += host.getNewLine();
for (var i = firstLine; i <= lastLine; i++) {
+ context += host.getNewLine();
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
i = lastLine - 1;
@@ -59920,9 +60203,7 @@ var ts;
output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
output += " - ";
}
- var categoryColor = getCategoryFormat(diagnostic.category);
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- output += formatColorAndReset(category, categoryColor);
+ output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file) {
@@ -61991,12 +62272,14 @@ var ts;
var filesWithChangedSetOfUnresolvedImports;
var filesWithInvalidatedResolutions;
var allFilesHaveInvalidatedResolution = false;
- var resolvedModuleNames = ts.createMap();
- var perDirectoryResolvedModuleNames = ts.createMap();
- var resolvedTypeReferenceDirectives = ts.createMap();
- var perDirectoryResolvedTypeReferenceDirectives = ts.createMap();
var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); });
var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
+ var resolvedModuleNames = ts.createMap();
+ var perDirectoryResolvedModuleNames = ts.createMap();
+ var nonRelaticeModuleNameCache = ts.createMap();
+ var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
+ var resolvedTypeReferenceDirectives = ts.createMap();
+ var perDirectoryResolvedTypeReferenceDirectives = ts.createMap();
var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"];
var customFailedLookupPaths = ts.createMap();
var directoryWatchesOfFailedLookups = ts.createMap();
@@ -62057,6 +62340,7 @@ var ts;
}
function clearPerDirectoryResolutions() {
perDirectoryResolvedModuleNames.clear();
+ nonRelaticeModuleNameCache.clear();
perDirectoryResolvedTypeReferenceDirectives.clear();
}
function finishCachingPerDirectoryResolution() {
@@ -62070,7 +62354,7 @@ var ts;
clearPerDirectoryResolutions();
}
function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host);
+ var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache);
if (!resolutionHost.getGlobalCache) {
return primaryResult;
}
@@ -62110,15 +62394,8 @@ var ts;
perDirectoryResolution.set(name, resolution);
}
resolutionsInFile.set(name, resolution);
- if (resolution.failedLookupLocations) {
- if (existingResolution && existingResolution.failedLookupLocations) {
- watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution);
- }
- else {
- watchFailedLookupLocationOfResolution(resolution, 0);
- }
- }
- else if (existingResolution) {
+ watchFailedLookupLocationOfResolution(resolution);
+ if (existingResolution) {
stopWatchFailedLookupLocationOfResolution(existingResolution);
}
if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
@@ -62213,69 +62490,87 @@ var ts;
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
}
- function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) {
- var failedLookupLocations = resolution.failedLookupLocations;
- var existingFailedLookupLocations = existingResolution.failedLookupLocations;
- for (var index = 0; index < failedLookupLocations.length; index++) {
- if (index === existingFailedLookupLocations.length) {
- watchFailedLookupLocationOfResolution(resolution, index);
- return;
- }
- else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) {
- watchFailedLookupLocationOfResolution(resolution, index);
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index);
- return;
- }
+ function watchFailedLookupLocationOfResolution(resolution) {
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length);
- }
- function watchFailedLookupLocationOfResolution(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ if (resolution.refCount !== undefined) {
+ resolution.refCount++;
+ return;
+ }
+ resolution.refCount = 1;
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var setAtRoot = false;
+ for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
- customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
- }
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore;
if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- if (dirWatcher) {
- dirWatcher.refCount++;
+ if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
+ }
+ if (dirPath === rootPath) {
+ setAtRoot = true;
}
else {
- directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ setDirectoryWatcher(dir, dirPath);
}
}
}
+ if (setAtRoot) {
+ setDirectoryWatcher(rootDir, rootPath);
+ }
+ }
+ function setDirectoryWatcher(dir, dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (dirWatcher) {
+ dirWatcher.refCount++;
+ }
+ else {
+ directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ }
}
function stopWatchFailedLookupLocationOfResolution(resolution) {
- if (resolution.failedLookupLocations) {
- stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0);
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- }
- function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ resolution.refCount--;
+ if (resolution.refCount) {
+ return;
+ }
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var removeAtRoot = false;
+ for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
- if (refCount) {
- if (refCount === 1) {
- customFailedLookupPaths.delete(failedLookupLocationPath);
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
+ if (!ignore) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
+ if (refCount) {
+ if (refCount === 1) {
+ customFailedLookupPaths.delete(failedLookupLocationPath);
+ }
+ else {
+ ts.Debug.assert(refCount > 1);
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ }
+ }
+ if (dirPath === rootPath) {
+ removeAtRoot = true;
}
else {
- ts.Debug.assert(refCount > 1);
- customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ removeDirectoryWatcher(dirPath);
}
}
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore;
- if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- dirWatcher.refCount--;
- }
}
+ if (removeAtRoot) {
+ removeDirectoryWatcher(rootPath);
+ }
+ }
+ function removeDirectoryWatcher(dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ dirWatcher.refCount--;
}
function createDirectoryWatcher(directory, dirPath) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
@@ -62433,6 +62728,7 @@ var ts;
ts.createDiagnosticReporter = createDiagnosticReporter;
function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
if (system.clearScreen &&
+ !options.preserveWatchOutput &&
diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code &&
!options.extendedDiagnostics &&
!options.diagnostics) {
@@ -62851,6 +63147,9 @@ var ts;
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
}
else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
+ if (hostSourceFileInfo.fileWatcher) {
+ hostSourceFileInfo.fileWatcher.close();
+ }
sourceFilesCache.delete(oldSourceFile.path);
resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
}
@@ -63048,6 +63347,13 @@ var ts;
category: ts.Diagnostics.Command_line_Options,
description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
},
+ {
+ name: "preserveWatchOutput",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
+ },
{
name: "watch",
shortName: "w",
@@ -63125,9 +63431,10 @@ var ts;
"es2017.string": "lib.es2017.string.d.ts",
"es2017.intl": "lib.es2017.intl.d.ts",
"es2017.typedarrays": "lib.es2017.typedarrays.d.ts",
+ "es2018.promise": "lib.es2018.promise.d.ts",
+ "es2018.regexp": "lib.es2018.regexp.d.ts",
"esnext.array": "lib.esnext.array.d.ts",
"esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
- "esnext.promise": "lib.esnext.promise.d.ts",
}),
},
showInSimplifiedHelpView: true,
diff --git a/lib/tsserver.js b/lib/tsserver.js
index 103918e21dc..bf763b4bac7 100644
--- a/lib/tsserver.js
+++ b/lib/tsserver.js
@@ -826,10 +826,12 @@ var ts;
var InferencePriority;
(function (InferencePriority) {
InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
- InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType";
- InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType";
- InferencePriority[InferencePriority["NoConstraints"] = 8] = "NoConstraints";
- InferencePriority[InferencePriority["AlwaysStrict"] = 16] = "AlwaysStrict";
+ InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
+ InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint";
+ InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType";
+ InferencePriority[InferencePriority["NoConstraints"] = 16] = "NoConstraints";
+ InferencePriority[InferencePriority["AlwaysStrict"] = 32] = "AlwaysStrict";
+ InferencePriority[InferencePriority["PriorityImpliesUnion"] = 12] = "PriorityImpliesUnion";
})(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
var InferenceFlags;
(function (InferenceFlags) {
@@ -857,8 +859,15 @@ var ts;
(function (DiagnosticCategory) {
DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
- DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message";
+ DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
+ DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
})(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
+ function diagnosticCategoryName(d, lowerCase) {
+ if (lowerCase === void 0) { lowerCase = true; }
+ var name = DiagnosticCategory[d.category];
+ return lowerCase ? name.toLowerCase() : name;
+ }
+ ts.diagnosticCategoryName = diagnosticCategoryName;
var ModuleResolutionKind;
(function (ModuleResolutionKind) {
ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
@@ -1254,6 +1263,46 @@ var ts;
ListFormat[ListFormat["Parameters"] = 1296] = "Parameters";
ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters";
})(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
+ var PragmaKindFlags;
+ (function (PragmaKindFlags) {
+ PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
+ PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
+ PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
+ PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
+ PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
+ PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
+ })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
+ function _contextuallyTypePragmas(args) {
+ return args;
+ }
+ ts.commentPragmas = _contextuallyTypePragmas({
+ "reference": {
+ args: [
+ { name: "types", optional: true, captureSpan: true },
+ { name: "path", optional: true, captureSpan: true },
+ { name: "no-default-lib", optional: true }
+ ],
+ kind: 1
+ },
+ "amd-dependency": {
+ args: [{ name: "path" }, { name: "name", optional: true }],
+ kind: 1
+ },
+ "amd-module": {
+ args: [{ name: "name" }],
+ kind: 1
+ },
+ "ts-check": {
+ kind: 2
+ },
+ "ts-nocheck": {
+ kind: 2
+ },
+ "jsx": {
+ args: [{ name: "factory" }],
+ kind: 4
+ },
+ });
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -1315,7 +1364,7 @@ var ts;
var ts;
(function (ts) {
ts.versionMajorMinor = "2.8";
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".0";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -2373,19 +2422,21 @@ var ts;
}
ts.equalOwnProperties = equalOwnProperties;
function arrayToMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = createMap();
for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
var value = array_6[_i];
- result.set(makeKey(value), makeValue ? makeValue(value) : value);
+ result.set(makeKey(value), makeValue(value));
}
return result;
}
ts.arrayToMap = arrayToMap;
function arrayToNumericMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = [];
for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
var value = array_7[_i];
- result[makeKey(value)] = makeValue ? makeValue(value) : value;
+ result[makeKey(value)] = makeValue(value);
}
return result;
}
@@ -2394,6 +2445,20 @@ var ts;
return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; });
}
ts.arrayToSet = arrayToSet;
+ function arrayToMultiMap(values, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
+ var result = createMultiMap();
+ for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
+ var value = values_1[_i];
+ result.add(makeKey(value), makeValue(value));
+ }
+ return result;
+ }
+ ts.arrayToMultiMap = arrayToMultiMap;
+ function group(values, getGroupId) {
+ return arrayFrom(arrayToMultiMap(values, getGroupId).values());
+ }
+ ts.group = group;
function cloneMap(map) {
var clone = createMap();
copyEntries(map, clone);
@@ -2451,15 +2516,6 @@ var ts;
}
}
}
- function group(values, getGroupId) {
- var groupIdToGroup = createMultiMap();
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- groupIdToGroup.add(getGroupId(value), value);
- }
- return arrayFrom(groupIdToGroup.values());
- }
- ts.group = group;
function isArray(value) {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
@@ -2567,7 +2623,6 @@ var ts;
return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; });
}
ts.formatStringFromArgs = formatStringFromArgs;
- ts.localizedDiagnosticMessages = undefined;
function getLocaleSpecificMessage(message) {
return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
}
@@ -3333,7 +3388,7 @@ var ts;
}
includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive);
var _loop_2 = function (includeBasePath) {
- if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
+ if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
basePaths.push(includeBasePath);
}
};
@@ -3690,7 +3745,7 @@ var ts;
}
ts.matchedText = matchedText;
function findBestPatternMatch(values, getPattern, candidate) {
- var matchedValue = undefined;
+ var matchedValue;
var longestMatchPrefixLength = -1;
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
var v = values_2[_i];
@@ -4808,6 +4863,7 @@ var ts;
Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
+ Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
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}'."),
@@ -4879,7 +4935,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}'."),
- 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.Message, "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."),
+ 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}'."),
Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
@@ -5052,7 +5108,7 @@ var ts;
Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
- Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."),
+ Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
@@ -5096,6 +5152,7 @@ var ts;
Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."),
+ Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."),
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."),
@@ -5175,10 +5232,15 @@ var ts;
JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
+ JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
+ File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
+ This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
+ Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
+ JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
@@ -5219,6 +5281,9 @@ var ts;
Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
+ Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
+ Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
+ Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
};
})(ts || (ts = {}));
var ts;
@@ -5430,8 +5495,10 @@ var ts;
}
ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
- var directoryToModuleNameMap = ts.createMap();
- var moduleNameToDirectoryMap = ts.createMap();
+ return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName);
+ }
+ ts.createModuleResolutionCache = createModuleResolutionCache;
+ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
function getOrCreateCacheForDirectory(directoryName) {
var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
@@ -5497,7 +5564,7 @@ var ts;
}
}
}
- ts.createModuleResolutionCache = createModuleResolutionCache;
+ ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
@@ -5508,7 +5575,7 @@ var ts;
var result = perFolderCache && perFolderCache.get(moduleName);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
}
else {
@@ -5630,7 +5697,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
}
- var matchedPattern = undefined;
+ var matchedPattern;
if (state.compilerOptions.paths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
@@ -6042,6 +6109,7 @@ var ts;
}
return packageName;
}
+ ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage;
function getPackageNameFromAtTypesDirectory(mangledName) {
var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
if (withoutAtTypePrefix !== mangledName) {
@@ -6060,7 +6128,7 @@ var ts;
var result = cache && cache.get(containingDirectory);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
}
@@ -6443,8 +6511,7 @@ var ts;
}
ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
function isAmbientModule(node) {
- return node && node.kind === 237 &&
- (node.name.kind === 9 || isGlobalScopeAugmentation(node));
+ return ts.isModuleDeclaration(node) && (node.name.kind === 9 || isGlobalScopeAugmentation(node));
}
ts.isAmbientModule = isAmbientModule;
function isModuleWithStringLiteralName(node) {
@@ -6473,18 +6540,19 @@ var ts;
}
ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
function isExternalModuleAugmentation(node) {
- if (!node || !isAmbientModule(node)) {
- return false;
- }
+ return isAmbientModule(node) && isModuleAugmentationExternal(node);
+ }
+ ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ function isModuleAugmentationExternal(node) {
switch (node.parent.kind) {
case 272:
return ts.isExternalModule(node.parent);
case 238:
- return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
+ return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
}
return false;
}
- ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
function isEffectiveExternalModule(node, compilerOptions) {
return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
}
@@ -7690,14 +7758,7 @@ var ts;
}
ts.isNodeDescendantOf = isNodeDescendantOf;
function isDeclarationName(name) {
- switch (name.kind) {
- case 71:
- case 9:
- case 8:
- return ts.isDeclaration(name.parent) && name.parent.name === name;
- default:
- return false;
- }
+ return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
}
ts.isDeclarationName = isDeclarationName;
function isAnyDeclarationName(name) {
@@ -7810,38 +7871,6 @@ var ts;
return undefined;
}
ts.getAncestor = getAncestor;
- function getFileReferenceFromReferencePath(comment, commentRange) {
- var simpleReferenceRegEx = /^\/\/\/\s*= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
}
ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
function textSpanIntersectsWith(span, start, length) {
- var end = start + length;
- return start <= textSpanEnd(span) && end >= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
}
ts.textSpanIntersectsWith = textSpanIntersectsWith;
function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
@@ -9330,12 +9346,9 @@ var ts;
}
ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
function textSpanIntersection(span1, span2) {
- var intersectStart = Math.max(span1.start, span2.start);
- var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
- if (intersectStart <= intersectEnd) {
- return createTextSpanFromBounds(intersectStart, intersectEnd);
- }
- return undefined;
+ var start = Math.max(span1.start, span2.start);
+ var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
+ return start <= end ? createTextSpanFromBounds(start, end) : undefined;
}
ts.textSpanIntersection = textSpanIntersection;
function createTextSpan(start, length) {
@@ -13325,7 +13338,8 @@ var ts;
sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
sourceFile.flags = contextFlags;
nextToken();
- processReferenceComments(sourceFile);
+ processCommentPragmas(sourceFile, sourceText);
+ processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
sourceFile.statements = parseList(0, parseStatement);
ts.Debug.assert(token() === 1);
sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
@@ -13338,6 +13352,9 @@ var ts;
fixupParentReferences(sourceFile);
}
return sourceFile;
+ function reportPragmaDiagnostic(pos, end, diagnostic) {
+ parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
+ }
}
function addJSDocComment(node) {
var comments = ts.getJSDocCommentRanges(node, sourceFile.text);
@@ -15593,8 +15610,8 @@ var ts;
var fullStart = scanner.getStartPos();
parseExpected(27);
if (token() === 29) {
- parseExpected(29);
var node_1 = createNode(258, fullStart);
+ scanJsxText();
return finishNode(node_1);
}
var tagName = parseJsxElementName();
@@ -15633,7 +15650,9 @@ var ts;
}
function parseJsxExpression(inExpressionContext) {
var node = createNode(263);
- parseExpected(17);
+ if (!parseExpected(17)) {
+ return undefined;
+ }
if (token() !== 18) {
node.dotDotDotToken = parseOptionalToken(24);
node.expression = parseAssignmentExpressionOrHigher();
@@ -16057,7 +16076,7 @@ var ts;
parseExpected(88);
var awaitToken = parseOptionalToken(121);
parseExpected(19);
- var initializer = undefined;
+ var initializer;
if (token() !== 25) {
if (token() === 104 || token() === 110 || token() === 76) {
initializer = parseVariableDeclarationList(true);
@@ -17071,84 +17090,6 @@ var ts;
parseSemicolon();
return finishNode(node);
}
- function processReferenceComments(sourceFile) {
- var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText);
- var referencedFiles = [];
- var typeReferenceDirectives = [];
- var amdDependencies = [];
- var amdModuleName;
- var checkJsDirective = undefined;
- while (true) {
- var kind = triviaScanner.scan();
- if (kind !== 2) {
- if (ts.isTrivia(kind)) {
- continue;
- }
- else {
- break;
- }
- }
- var range = {
- kind: triviaScanner.getToken(),
- pos: triviaScanner.getTokenPos(),
- end: triviaScanner.getTextPos(),
- };
- var comment = sourceText.substring(range.pos, range.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range);
- if (referencePathMatchResult) {
- var fileReference = referencePathMatchResult.fileReference;
- sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var diagnosticMessage = referencePathMatchResult.diagnosticMessage;
- if (fileReference) {
- if (referencePathMatchResult.isTypeReferenceDirective) {
- typeReferenceDirectives.push(fileReference);
- }
- else {
- referencedFiles.push(fileReference);
- }
- }
- if (diagnosticMessage) {
- parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage));
- }
- }
- else {
- var amdModuleNameRegEx = /^\/\/\/\s* context.checkJsDirective.pos) {
+ context.checkJsDirective = {
+ enabled: key === "ts-check",
+ end: entry.range.end,
+ pos: entry.range.pos
+ };
+ }
+ });
+ break;
+ }
+ case "jsx": return;
+ default: ts.Debug.fail("Unhandled pragma kind");
+ }
+ });
+ }
+ ts.processPragmasIntoFields = processPragmasIntoFields;
+ var namedArgRegExCache = ts.createMap();
+ function getNamedArgRegEx(name) {
+ if (namedArgRegExCache.has(name)) {
+ return namedArgRegExCache.get(name);
+ }
+ var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
+ namedArgRegExCache.set(name, result);
+ return result;
+ }
+ var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
+ var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
+ function extractPragmas(pragmas, range, text) {
+ var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text);
+ if (tripleSlash) {
+ var name = tripleSlash[1].toLowerCase();
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & 1)) {
+ return;
+ }
+ if (pragma.args) {
+ var argument = {};
+ for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
+ var arg = _a[_i];
+ var matcher = getNamedArgRegEx(arg.name);
+ var matchResult = matcher.exec(text);
+ if (!matchResult && !arg.optional) {
+ return;
+ }
+ else if (matchResult) {
+ if (arg.captureSpan) {
+ var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
+ argument[arg.name] = {
+ value: matchResult[3],
+ pos: startPos,
+ end: startPos + matchResult[3].length
+ };
+ }
+ else {
+ argument[arg.name] = matchResult[3];
+ }
+ }
+ }
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ }
+ else {
+ pragmas.push({ name: name, args: { arguments: {}, range: range } });
+ }
+ return;
+ }
+ var singleLine = singleLinePragmaRegEx.exec(text);
+ if (singleLine) {
+ return addPragmaForMatch(pragmas, range, 2, singleLine);
+ }
+ var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim;
+ var multiLineMatch;
+ while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
+ addPragmaForMatch(pragmas, range, 4, multiLineMatch);
+ }
+ }
+ function addPragmaForMatch(pragmas, range, kind, match) {
+ if (!match)
+ return;
+ var name = match[1].toLowerCase();
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & kind)) {
+ return;
+ }
+ var args = match[2];
+ var argument = getNamedPragmaArguments(pragma, args);
+ if (argument === "fail")
+ return;
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ return;
+ }
+ function getNamedPragmaArguments(pragma, text) {
+ if (!text)
+ return {};
+ if (!pragma.args)
+ return {};
+ var args = text.split(/\s+/);
+ var argMap = {};
+ for (var i = 0; i < pragma.args.length; i++) {
+ var argument = pragma.args[i];
+ if (!args[i] && !argument.optional) {
+ return "fail";
+ }
+ if (argument.captureSpan) {
+ return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
+ }
+ argMap[argument.name] = args[i];
+ }
+ return argMap;
+ }
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -18341,7 +18476,7 @@ var ts;
ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
}
- return ts.getEscapedTextOfIdentifierOrLiteral(name);
+ return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
switch (node.kind) {
case 154:
@@ -18435,7 +18570,12 @@ var ts;
}
}
addDeclarationToSymbol(symbol, node, includes);
- symbol.parent = parent;
+ if (symbol.parent) {
+ ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ symbol.parent = parent;
+ }
return symbol;
}
function declareModuleMember(node, symbolFlags, symbolExcludes) {
@@ -19400,7 +19540,7 @@ var ts;
if (ts.hasModifier(node, 1)) {
errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
- if (ts.isExternalModuleAugmentation(node)) {
+ if (ts.isModuleAugmentationExternal(node)) {
declareModuleSymbol(node);
}
else {
@@ -19415,9 +19555,7 @@ var ts;
}
}
var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639);
- if (pattern) {
- (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol });
- }
+ file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
}
}
else {
@@ -19743,7 +19881,7 @@ var ts;
seenThisKeyword = true;
return;
case 160:
- return checkTypePredicate(node);
+ break;
case 147:
return bindTypeParameter(node);
case 148:
@@ -19857,16 +19995,6 @@ var ts;
function bindAnonymousTypeWorker(node) {
return bindAnonymousDeclaration(node, 2048, "__type");
}
- function checkTypePredicate(node) {
- var parameterName = node.parameterName, type = node.type;
- if (parameterName && parameterName.kind === 71) {
- checkStrictModeIdentifier(parameterName);
- }
- if (parameterName && parameterName.kind === 173) {
- seenThisKeyword = true;
- }
- bind(type);
- }
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (ts.isExternalModule(file)) {
@@ -21278,7 +21406,7 @@ var ts;
node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement);
return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined;
},
- getJsxIntrinsicTagNames: getJsxIntrinsicTagNames,
+ getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
isOptionalParameter: function (node) {
node = ts.getParseTreeNode(node, ts.isParameter);
return node ? isOptionalParameter(node) : false;
@@ -21315,7 +21443,7 @@ var ts;
resolveName: function (name, location, meaning, excludeGlobals) {
return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals);
},
- getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); },
+ getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
@@ -21327,13 +21455,13 @@ var ts;
node = ts.getParseTreeNode(node, ts.isTypeNode);
return node && getTypeArgumentConstraint(node);
},
+ getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; },
};
var tupleTypes = [];
var unionTypes = ts.createMap();
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
- var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4, "unknown");
@@ -21395,6 +21523,7 @@ var ts;
var anyArrayType;
var autoArrayType;
var anyReadonlyArrayType;
+ var deferredGlobalNonNullableTypeAlias;
var deferredGlobalESSymbolConstructorSymbol;
var deferredGlobalESSymbolType;
var deferredGlobalTypedPropertyDescriptorType;
@@ -21408,9 +21537,6 @@ var ts;
var deferredGlobalAsyncIteratorType;
var deferredGlobalAsyncIterableIteratorType;
var deferredGlobalTemplateStringsArrayType;
- var deferredJsxElementClassType;
- var deferredJsxElementType;
- var deferredJsxStatelessElementType;
var deferredNodes;
var deferredUnusedIdentifierNodes;
var flowLoopStart = 0;
@@ -21437,6 +21563,18 @@ var ts;
var potentialNewTargetCollisions = [];
var awaitedTypeStack = [];
var diagnostics = ts.createDiagnosticCollection();
+ var suggestionDiagnostics = ts.createMultiMap();
+ function addSuggestionDiagnostic(diag) {
+ suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
+ }
+ function addErrorOrSuggestionDiagnostic(isError, diag) {
+ if (isError) {
+ diagnostics.add(diag);
+ }
+ else {
+ addSuggestionDiagnostic(diag);
+ }
+ }
var TypeFacts;
(function (TypeFacts) {
TypeFacts[TypeFacts["None"] = 0] = "None";
@@ -21462,8 +21600,7 @@ var ts;
TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull";
TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy";
TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy";
- TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable";
- TypeFacts[TypeFacts["All"] = 8388607] = "All";
+ TypeFacts[TypeFacts["All"] = 4194303] = "All";
TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts";
TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts";
TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts";
@@ -21490,10 +21627,10 @@ var ts;
TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts";
TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts";
TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts";
- TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts";
- TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts";
- TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts";
- TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts";
+ TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts";
+ TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts";
+ TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts";
+ TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts";
TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts";
TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts";
})(TypeFacts || (TypeFacts = {}));
@@ -21525,11 +21662,6 @@ var ts;
var typeofType = createTypeofType();
var _jsxNamespace;
var _jsxFactoryEntity;
- var _jsxElementPropertiesName;
- var _hasComputedJsxElementPropertiesName = false;
- var _jsxElementChildrenPropertyName;
- var _hasComputedJsxElementChildrenPropertyName = false;
- var jsxTypes = ts.createUnderscoreEscapedMap();
var subtypeRelation = ts.createMap();
var assignableRelation = ts.createMap();
var definitelyAssignableRelation = ts.createMap();
@@ -21585,6 +21717,7 @@ var ts;
TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType";
TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject";
TypeIncludes[TypeIncludes["Union"] = 2048] = "Union";
+ TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard";
})(TypeIncludes || (TypeIncludes = {}));
var MembersOrExportsResolutionKind;
(function (MembersOrExportsResolutionKind) {
@@ -21729,7 +21862,23 @@ var ts;
};
}
}
- function getJsxNamespace() {
+ function getJsxNamespace(location) {
+ if (location) {
+ var file = ts.getSourceFileOfNode(location);
+ if (file) {
+ if (file.localJsxNamespace) {
+ return file.localJsxNamespace;
+ }
+ var jsxPragma = file.pragmas.get("jsx");
+ if (jsxPragma) {
+ var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
+ file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
+ if (file.localJsxFactory) {
+ return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
+ }
+ }
+ }
+ }
if (!_jsxNamespace) {
_jsxNamespace = "React";
if (compilerOptions.jsxFactory) {
@@ -22547,7 +22696,15 @@ var ts;
combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
symbolFromModule || symbolFromVariable;
if (!symbol) {
- error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name));
+ var moduleName = getFullyQualifiedName(moduleSymbol);
+ var declarationName = ts.declarationNameToString(name);
+ var suggestion = getSuggestionForNonexistentModule(name, targetSymbol);
+ if (suggestion !== undefined) {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion);
+ }
+ else {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
+ }
}
return symbol;
}
@@ -22732,6 +22889,9 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
+ if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) {
+ addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
+ }
return getMergedSymbol(sourceFile.symbol);
}
if (moduleNotFoundError) {
@@ -22750,10 +22910,8 @@ var ts;
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
}
- else if (noImplicitAny && moduleNotFoundError) {
- var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name);
- errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName);
- diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo));
+ else {
+ addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
}
return undefined;
}
@@ -22774,6 +22932,11 @@ var ts;
}
return undefined;
}
+ function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) {
+ var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
+ var errorInfo = packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name));
+ return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
+ }
function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol;
}
@@ -23029,11 +23192,19 @@ var ts;
function getQualifiedLeftMeaning(rightMeaning) {
return rightMeaning === 107455 ? 107455 : 1920;
}
- function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) {
+ function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
+ if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
return undefined;
}
- var visitedSymbolTables = [];
+ var id = "" + getSymbolId(symbol);
+ var visitedSymbolTables;
+ if (visitedSymbolTablesMap.has(id)) {
+ visitedSymbolTables = visitedSymbolTablesMap.get(id);
+ }
+ else {
+ visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
+ }
return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
@@ -23045,7 +23216,7 @@ var ts;
}
function canQualifySymbol(symbolFromSymbolTable, meaning) {
return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
- !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing);
+ !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
}
function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) &&
@@ -23059,6 +23230,7 @@ var ts;
return ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
if (symbolFromSymbolTable.flags & 2097152
&& symbolFromSymbolTable.escapedName !== "export="
+ && symbolFromSymbolTable.escapedName !== "default"
&& !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
&& (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) {
var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
@@ -23249,6 +23421,7 @@ var ts;
}
}
function typeToString(type, enclosingDeclaration, flags, writer) {
+ if (flags === void 0) { flags = 1048576; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960, writer);
ts.Debug.assert(typeNode !== undefined, "should always get typenode");
@@ -23374,6 +23547,9 @@ var ts;
}
if (type.flags & 1024) {
if (!(context.flags & 1048576)) {
+ if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
+ return ts.createTypeQueryNode(symbolToName(type.symbol, context, 107455, false));
+ }
if (context.tracker.reportInaccessibleUniqueSymbolError) {
context.tracker.reportInaccessibleUniqueSymbolError();
}
@@ -23454,8 +23630,8 @@ var ts;
if (type.flags & 2097152) {
var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
- var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
- var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
+ var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
+ var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
if (type.flags & 4194304) {
@@ -23613,7 +23789,7 @@ var ts;
}
}
}
- var entityName = undefined;
+ var entityName = void 0;
var nameIdentifier = symbolToTypeReferenceName(type.symbol);
if (qualifiedName) {
ts.Debug.assert(!qualifiedName.right);
@@ -24041,8 +24217,8 @@ var ts;
return "(Anonymous function)";
}
}
- if (symbol.syntheticLiteralTypeOrigin) {
- var stringValue = symbol.syntheticLiteralTypeOrigin.value;
+ if (symbol.nameType && symbol.nameType.flags & 32) {
+ var stringValue = symbol.nameType.value;
if (!ts.isIdentifierText(stringValue, compilerOptions.target)) {
return "\"" + ts.escapeString(stringValue, 34) + "\"";
}
@@ -24305,7 +24481,7 @@ var ts;
parentType = getNonNullableType(parentType);
}
var propType = getTypeOfPropertyOfType(parentType, text);
- var declaredType = propType && getApparentTypeForLocation(propType, declaration.name);
+ var declaredType = propType && getConstraintForLocation(propType, declaration.name);
type = declaredType && getFlowTypeOfReference(declaration, declaredType) ||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) ||
getIndexTypeOfType(parentType, 0);
@@ -25391,8 +25567,17 @@ var ts;
error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3);
lateSymbol = createSymbol(0, memberName, 1024);
}
+ var symbolLinks_1 = getSymbolLinks(lateSymbol);
+ if (!symbolLinks_1.nameType) {
+ symbolLinks_1.nameType = type;
+ }
addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
- lateSymbol.parent = parent;
+ if (lateSymbol.parent) {
+ ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ lateSymbol.parent = parent;
+ }
return links.resolvedSymbol = lateSymbol;
}
}
@@ -25575,7 +25760,7 @@ var ts;
}
return [signature];
}
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true);
if (!match) {
@@ -25587,7 +25772,7 @@ var ts;
}
function getUnionSignatures(types, kind) {
var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); });
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
var signature = _a[_i];
@@ -25703,7 +25888,7 @@ var ts;
}
else {
var members = emptySymbols;
- var stringIndexInfo = undefined;
+ var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
}
@@ -25783,11 +25968,10 @@ var ts;
if (typeof propertySymbolOrIndex === "object") {
propertySymbol = propertySymbolOrIndex;
}
- var iterationMapper = createTypeMapper([typeParameter], [t]);
- var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper;
+ var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t]));
var propType = instantiateType(templateType, templateMapper);
if (t.flags & 32) {
- var propName = ts.escapeLeadingUnderscores(t.value);
+ var propName = getLateBoundNameFromType(t);
var modifiersProp = getPropertyOfType(modifiersType, propName);
var isOptional = !!(templateModifiers & 4 ||
!(templateModifiers & 8) && modifiersProp && modifiersProp.flags & 16777216);
@@ -25801,7 +25985,7 @@ var ts;
prop.syntheticOrigin = propertySymbol;
prop.declarations = propertySymbol.declarations;
}
- prop.syntheticLiteralTypeOrigin = t;
+ prop.nameType = t;
members.set(propName, prop);
}
else if (t.flags & (1 | 2)) {
@@ -25971,16 +26155,14 @@ var ts;
return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined;
}
function getDefaultConstraintOfConditionalType(type) {
- return getUnionType([type.trueType, type.falseType]);
+ return getUnionType([getTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]);
}
function getConstraintOfDistributiveConditionalType(type) {
- if (isDistributiveConditionalType(type)) {
+ if (type.root.isDistributive) {
var constraint = getConstraintOfType(type.checkType);
if (constraint) {
- var target = type.target || type;
- var mapper = createTypeMapper([target.checkType], [constraint]);
- var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper;
- return instantiateType(target, combinedMapper);
+ var mapper = createTypeMapper([type.root.checkType], [constraint]);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
}
}
return undefined;
@@ -25988,17 +26170,23 @@ var ts;
function getConstraintOfConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
- function getBaseConstraintOfType(type) {
+ function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) {
if (type.flags & (7372800 | 393216)) {
var constraint = getResolvedBaseConstraint(type);
if (constraint !== noConstraintType && constraint !== circularConstraintType) {
return constraint;
}
}
- else if (type.flags & 524288) {
+ }
+ function getBaseConstraintOfType(type) {
+ var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type);
+ if (!constraint && type.flags & 524288) {
return stringType;
}
- return undefined;
+ return constraint;
+ }
+ function getBaseConstraintOrType(type) {
+ return getBaseConstraintOfType(type) || type;
}
function hasNonCircularBaseConstraint(type) {
return getResolvedBaseConstraint(type) !== circularConstraintType;
@@ -26057,7 +26245,8 @@ var ts;
return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 2097152) {
- return getBaseConstraint(getConstraintOfConditionalType(t));
+ var constraint = getConstraintOfConditionalType(t);
+ return constraint && getBaseConstraint(constraint);
}
if (t.flags & 4194304) {
return getBaseConstraint(t.substitute);
@@ -26149,7 +26338,7 @@ var ts;
}
var propTypes = [];
var declarations = [];
- var commonType = undefined;
+ var commonType;
for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
var prop = props_1[_b];
if (prop.declarations) {
@@ -26365,7 +26554,7 @@ var ts;
var parameters = [];
var hasLiteralTypes = false;
var minArgumentCount = 0;
- var thisParameter = undefined;
+ var thisParameter = void 0;
var hasThisParameter = void 0;
var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
@@ -27081,11 +27270,6 @@ var ts;
var symbol = getGlobalSymbol(name, 793064, undefined);
return symbol && getTypeOfGlobalSymbol(symbol, arity);
}
- function getExportedTypeFromNamespace(namespace, name) {
- var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined);
- var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064);
- return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol);
- }
function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
}
@@ -27185,6 +27369,8 @@ var ts;
}
else if (flags & 1) {
includes |= 1;
+ if (type === wildcardType)
+ includes |= 4096;
}
else if (!strictNullChecks && flags & 12288) {
if (flags & 4096)
@@ -27292,7 +27478,7 @@ var ts;
var typeSet = [];
var includes = addTypesToUnion(typeSet, 0, types);
if (includes & 1) {
- return anyType;
+ return includes & 4096 ? wildcardType : anyType;
}
switch (unionReduction) {
case 1:
@@ -27376,6 +27562,8 @@ var ts;
}
else if (flags & 1) {
includes |= 1;
+ if (type === wildcardType)
+ includes |= 4096;
}
else if (flags & 16384) {
includes |= 8;
@@ -27414,7 +27602,7 @@ var ts;
return neverType;
}
if (includes & 1) {
- return anyType;
+ return includes & 4096 ? wildcardType : anyType;
}
if (includes & 1024 && !(includes & 512)) {
typeSet.push(emptyObjectType);
@@ -27454,19 +27642,30 @@ var ts;
return type.resolvedIndexType;
}
function getLiteralTypeFromPropertyName(prop) {
- return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ?
- neverType :
- getLiteralType(ts.symbolName(prop));
+ var links = getSymbolLinks(prop);
+ if (!links.nameType) {
+ if (links.target) {
+ ts.Debug.assert(links.target.escapedName === prop.escapedName, "Target symbol and symbol do not have the same name");
+ links.nameType = getLiteralTypeFromPropertyName(links.target);
+ }
+ else {
+ links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ?
+ neverType :
+ getLiteralType(ts.symbolName(prop));
+ }
+ }
+ return links.nameType;
}
function getLiteralTypeFromPropertyNames(type) {
return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName));
}
function getIndexType(type) {
- return maybeTypeOfKind(type, 7372800) ? getIndexTypeForGenericType(type) :
- ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) :
- type === wildcardType ? wildcardType :
- type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType :
- getLiteralTypeFromPropertyNames(type);
+ return type.flags & 262144 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) :
+ maybeTypeOfKind(type, 7372800) ? getIndexTypeForGenericType(type) :
+ ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) :
+ type === wildcardType ? wildcardType :
+ type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType :
+ getLiteralTypeFromPropertyNames(type);
}
function getIndexTypeOrString(type) {
var indexType = getIndexType(type);
@@ -27612,10 +27811,13 @@ var ts;
}
function substituteIndexedMappedType(objectType, type) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper;
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
}
function getIndexedAccessType(objectType, indexType, accessNode) {
+ if (objectType === wildcardType || indexType === wildcardType) {
+ return wildcardType;
+ }
if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 184) && isGenericObjectType(objectType)) {
if (objectType.flags & 1) {
return objectType;
@@ -27664,54 +27866,45 @@ var ts;
function getActualTypeParameter(type) {
return type.flags & 4194304 ? type.typeParameter : type;
}
- function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) {
- var type = createType(2097152);
- type.checkType = checkType;
- type.extendsType = extendsType;
- type.trueType = trueType;
- type.falseType = falseType;
- type.inferTypeParameters = inferTypeParameters;
- type.target = target;
- type.mapper = mapper;
- type.aliasSymbol = aliasSymbol;
- type.aliasTypeArguments = aliasTypeArguments;
- return type;
- }
- function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) {
- var extendsType = instantiateType(baseExtendsType, mapper);
- if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) {
- return instantiateType(baseFalseType, mapper);
+ function getConditionalType(root, mapper) {
+ var checkType = instantiateType(root.checkType, mapper);
+ var extendsType = instantiateType(root.extendsType, mapper);
+ if (checkType === wildcardType || extendsType === wildcardType) {
+ return wildcardType;
}
- var combinedMapper;
- if (inferTypeParameters) {
- var inferences = ts.map(inferTypeParameters, createInferenceInfo);
- inferTypes(inferences, checkType, extendsType, 8 | 16);
- var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; });
- var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes);
- combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper;
- }
- if (checkType.flags & 1 || (checkType.flags & 16384 && !(extendsType.flags & 16384))) {
- return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]);
- }
- var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType;
- if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) {
- return instantiateType(baseTrueType, combinedMapper || mapper);
+ if (!root.isDistributive || !maybeTypeOfKind(checkType, 7897088)) {
+ var combinedMapper = void 0;
+ if (root.inferTypeParameters) {
+ var context = createInferenceContext(root.inferTypeParameters, undefined, 0);
+ inferTypes(context.inferences, checkType, extendsType, 16 | 32);
+ combinedMapper = combineTypeMappers(mapper, context);
+ }
+ if (checkType.flags & 1) {
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ }
+ var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
+ if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) {
+ return instantiateType(root.falseType, mapper);
+ }
+ if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) {
+ return instantiateType(root.trueType, combinedMapper || mapper);
+ }
}
var erasedCheckType = getActualTypeParameter(checkType);
- var trueType = instantiateType(baseTrueType, mapper);
- var falseType = instantiateType(baseFalseType, mapper);
- var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 ? 1 : 0;
- var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive;
- var cached = conditionalTypes.get(id);
- if (cached) {
- return cached;
- }
- var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper));
- conditionalTypes.set(id, result);
+ var result = createType(2097152);
+ result.root = root;
+ result.checkType = erasedCheckType;
+ result.extendsType = extendsType;
+ result.mapper = mapper;
+ result.aliasSymbol = root.aliasSymbol;
+ result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper);
return result;
}
- function isDistributiveConditionalType(type) {
- return !!((type.target || type).checkType.flags & 32768);
+ function getTrueTypeFromConditionalType(type) {
+ return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
+ }
+ function getFalseTypeFromConditionalType(type) {
+ return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -27727,7 +27920,28 @@ var ts;
function getTypeFromConditionalTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), undefined, undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node));
+ var checkType = getTypeFromTypeNode(node.checkType);
+ var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ var allOuterTypeParameters = getOuterTypeParameters(node, true);
+ var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
+ var root = {
+ node: node,
+ checkType: checkType,
+ extendsType: getTypeFromTypeNode(node.extendsType),
+ trueType: getTypeFromTypeNode(node.trueType),
+ falseType: getTypeFromTypeNode(node.falseType),
+ isDistributive: !!(checkType.flags & 32768),
+ inferTypeParameters: getInferTypeParameters(node),
+ outerTypeParameters: outerTypeParameters,
+ instantiations: undefined,
+ aliasSymbol: getAliasSymbolForTypeNode(node),
+ aliasTypeArguments: aliasTypeArguments
+ };
+ links.resolvedType = getConditionalType(root, undefined);
+ if (outerTypeParameters) {
+ root.instantiations = ts.createMap();
+ root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
+ }
}
return links.resolvedType;
}
@@ -28054,14 +28268,18 @@ var ts;
return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
}
function isInferenceContext(mapper) {
- return !!mapper.signature;
+ return !!mapper.typeParameters;
}
function cloneTypeMapper(mapper) {
return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) :
+ createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) :
mapper;
}
function combineTypeMappers(mapper1, mapper2) {
+ if (!mapper1)
+ return mapper2;
+ if (!mapper2)
+ return mapper1;
return function (t) { return instantiateType(mapper1(t), mapper2); };
}
function createReplacementMapper(source, target, baseMapper) {
@@ -28213,19 +28431,29 @@ var ts;
return result;
}
function getConditionalTypeInstantiation(type, mapper) {
- var target = type.target || type;
- var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper;
- if (isDistributiveConditionalType(target)) {
- var checkType_1 = target.checkType;
- var instantiatedType = combinedMapper(checkType_1);
- if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072) {
- return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); });
+ var root = type.root;
+ if (root.outerTypeParameters) {
+ var typeArguments = ts.map(root.outerTypeParameters, mapper);
+ var id = getTypeListId(typeArguments);
+ var result = root.instantiations.get(id);
+ if (!result) {
+ var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
+ result = instantiateConditionalType(root, newMapper);
+ root.instantiations.set(id, result);
+ }
+ return result;
+ }
+ return type;
+ }
+ function instantiateConditionalType(root, mapper) {
+ if (root.isDistributive) {
+ var checkType_1 = root.checkType;
+ var instantiatedType = mapper(checkType_1);
+ if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 | 16384)) {
+ return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); });
}
}
- return instantiateConditionalType(target, combinedMapper);
- }
- function instantiateConditionalType(type, mapper) {
- return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments);
+ return getConditionalType(root, mapper);
}
function instantiateType(type, mapper) {
if (type && mapper && mapper !== identityMapper) {
@@ -28263,7 +28491,7 @@ var ts;
return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
}
if (type.flags & 2097152) {
- return getConditionalTypeInstantiation(type, mapper);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (type.flags & 4194304) {
return mapper(type.typeParameter);
@@ -28838,11 +29066,11 @@ var ts;
}
}
if (flags & 2097152) {
- if (result = isRelatedTo(source.checkType, target.checkType, false)) {
- if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) {
- if (result &= isRelatedTo(source.trueType, target.trueType, false)) {
- if (result &= isRelatedTo(source.falseType, target.falseType, false)) {
- if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) {
+ if (source.root.isDistributive === target.root.isDistributive) {
+ if (result = isRelatedTo(source.checkType, target.checkType, false)) {
+ if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) {
+ if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) {
+ if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) {
return result;
}
}
@@ -29188,20 +29416,11 @@ var ts;
}
}
else if (source.flags & 2097152) {
- if (relation !== definitelyAssignableRelation) {
- var constraint = getConstraintOfDistributiveConditionalType(source);
- if (constraint) {
- if (result = isRelatedTo(constraint, target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
- }
- }
- }
if (target.flags & 2097152) {
if (isTypeIdenticalTo(source.checkType, target.checkType) &&
isTypeIdenticalTo(source.extendsType, target.extendsType)) {
- if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
- result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
+ if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
+ result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -29209,9 +29428,21 @@ var ts;
}
}
}
- else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
+ else if (relation !== definitelyAssignableRelation) {
+ var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
+ if (distributiveConstraint) {
+ if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ var defaultConstraint = getDefaultConstraintOfConditionalType(source);
+ if (defaultConstraint) {
+ if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
}
}
else {
@@ -29933,8 +30164,17 @@ var ts;
ts.Debug.assert(strictNullChecks);
return type.flags & 4096 ? type : getUnionType([type, undefinedType]);
}
+ function getGlobalNonNullableTypeInstantiation(type) {
+ if (!deferredGlobalNonNullableTypeAlias) {
+ deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288, undefined) || unknownSymbol;
+ }
+ if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
+ return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
+ }
+ return getTypeWithFacts(type, 524288);
+ }
function getNonNullableType(type) {
- return strictNullChecks ? getTypeWithFacts(type, 524288) : type;
+ return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
}
function isObjectTypeWithInferableIndex(type) {
return type.symbol && (type.symbol.flags & (4096 | 2048 | 512)) !== 0 &&
@@ -30027,6 +30267,10 @@ var ts;
}
var result = createSymbol(4 | 16777216, name);
result.type = undefinedType;
+ var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (associatedKeyType.flags & 32) {
+ result.nameType = associatedKeyType;
+ }
undefinedProperties.set(name, result);
return result;
}
@@ -30173,9 +30417,10 @@ var ts;
callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
}
}
- function createInferenceContext(signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo);
+ function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
+ var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(typeParameters, createInferenceInfo);
var context = mapper;
+ context.typeParameters = typeParameters;
context.signature = signature;
context.inferences = inferences;
context.flags = flags;
@@ -30282,7 +30527,7 @@ var ts;
var templateType = getTemplateTypeFromMappedType(target);
var inference = createInferenceInfo(typeParameter);
inferTypes([inference], sourceType, templateType);
- return getTypeFromInference(inference) || emptyObjectType;
+ return getTypeFromInference(inference);
}
function getUnmatchedProperty(source, target, requireOptionalProperties) {
var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
@@ -30300,18 +30545,26 @@ var ts;
function getTypeFromInference(inference) {
return inference.candidates ? getUnionType(inference.candidates, 2) :
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
- undefined;
+ emptyObjectType;
}
function inferTypes(inferences, originalSource, originalTarget, priority) {
if (priority === void 0) { priority = 0; }
var symbolStack;
var visited;
var contravariant = false;
+ var propagationType;
inferFromTypes(originalSource, originalTarget);
function inferFromTypes(source, target) {
if (!couldContainTypeVariables(target)) {
return;
}
+ if (source.flags & 1) {
+ var savePropagationType = propagationType;
+ propagationType = source;
+ inferFromTypes(target, target);
+ propagationType = savePropagationType;
+ return;
+ }
if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
var sourceTypes = source.aliasTypeArguments;
var targetTypes = target.aliasTypeArguments;
@@ -30361,14 +30614,15 @@ var ts;
inference.priority = priority;
}
if (priority === inference.priority) {
+ var candidate = propagationType || source;
if (contravariant) {
- inference.contraCandidates = ts.append(inference.contraCandidates, source);
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
}
else {
- inference.candidates = ts.append(inference.candidates, source);
+ inference.candidates = ts.append(inference.candidates, candidate);
}
}
- if (!(priority & 4) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
}
}
@@ -30407,8 +30661,8 @@ var ts;
else if (source.flags & 2097152 && target.flags & 2097152) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(source.trueType, target.trueType);
- inferFromTypes(source.falseType, target.falseType);
+ inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
+ inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
}
else if (target.flags & 393216) {
var targetTypes = target.types;
@@ -30439,7 +30693,7 @@ var ts;
}
}
else {
- if (!(priority && 8 && source.flags & (262144 | 7897088))) {
+ if (!(priority & 16 && source.flags & (262144 | 7897088))) {
source = getApparentType(source);
}
if (source.flags & (65536 | 262144)) {
@@ -30466,7 +30720,7 @@ var ts;
}
}
function inferFromContravariantTypes(source, target) {
- if (strictFunctionTypes || priority & 16) {
+ if (strictFunctionTypes || priority & 32) {
contravariant = !contravariant;
inferFromTypes(source, target);
contravariant = !contravariant;
@@ -30507,7 +30761,10 @@ var ts;
return;
}
if (constraintType.flags & 32768) {
+ var savePriority = priority;
+ priority |= 4;
inferFromTypes(getIndexType(source), constraintType);
+ priority = savePriority;
inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target));
return;
}
@@ -30610,39 +30867,44 @@ var ts;
var inference = context.inferences[index];
var inferredType = inference.inferredType;
if (!inferredType) {
- if (inference.candidates) {
- var candidates = widenObjectLiteralCandidates(inference.candidates);
- var signature = context.signature;
- var widenLiteralTypes = inference.topLevel &&
- !hasPrimitiveConstraint(inference.typeParameter) &&
- (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
- var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
- var unwidenedType = context.flags & 1 || inference.priority & 4 ?
- getUnionType(baseCandidates, 2) :
- getCommonSupertype(baseCandidates);
- inferredType = getWidenedType(unwidenedType);
- if (inferredType.flags & 16384 && inference.contraCandidates) {
+ var signature = context.signature;
+ if (signature) {
+ if (inference.candidates) {
+ var candidates = widenObjectLiteralCandidates(inference.candidates);
+ var widenLiteralTypes = inference.topLevel &&
+ !hasPrimitiveConstraint(inference.typeParameter) &&
+ (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
+ var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
+ var unwidenedType = context.flags & 1 || inference.priority & 12 ?
+ getUnionType(baseCandidates, 2) :
+ getCommonSupertype(baseCandidates);
+ inferredType = getWidenedType(unwidenedType);
+ if (inferredType.flags & 16384 && inference.contraCandidates) {
+ inferredType = getCommonSubtype(inference.contraCandidates);
+ }
+ }
+ else if (inference.contraCandidates) {
inferredType = getCommonSubtype(inference.contraCandidates);
}
- }
- else if (inference.contraCandidates) {
- inferredType = getCommonSubtype(inference.contraCandidates);
- }
- else if (context.flags & 2) {
- inferredType = silentNeverType;
- }
- else {
- var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
- if (defaultType) {
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ else if (context.flags & 2) {
+ inferredType = silentNeverType;
}
else {
- inferredType = getDefaultTypeArgumentType(!!(context.flags & 4));
+ var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
+ if (defaultType) {
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ }
+ else {
+ inferredType = getDefaultTypeArgumentType(!!(context.flags & 4));
+ }
}
}
+ else {
+ inferredType = getTypeFromInference(inference);
+ }
inferredType = getWidenedUniqueESSymbolType(inferredType);
inference.inferredType = inferredType;
- var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]);
+ var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
var instantiatedConstraint = instantiateType(constraint, context);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
@@ -30676,7 +30938,7 @@ var ts;
function getFlowCacheKey(node) {
if (node.kind === 71) {
var symbol = getResolvedSymbol(node);
- return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
+ return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
}
if (node.kind === 99) {
return "0";
@@ -30885,8 +31147,8 @@ var ts;
}
if (flags & 65536) {
return isFunctionObjectType(type) ?
- strictNullChecks ? 6164448 : 8376288 :
- strictNullChecks ? 6166480 : 8378320;
+ strictNullChecks ? 1970144 : 4181984 :
+ strictNullChecks ? 1972176 : 4184016;
}
if (flags & (2048 | 4096)) {
return 2457472;
@@ -30898,7 +31160,7 @@ var ts;
return strictNullChecks ? 1981320 : 4193160;
}
if (flags & 134217728) {
- return strictNullChecks ? 6166480 : 8378320;
+ return strictNullChecks ? 1972176 : 4184016;
}
if (flags & 7897088) {
return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType);
@@ -30906,7 +31168,7 @@ var ts;
if (flags & 393216) {
return getTypeFactsOfTypes(type.types);
}
- return 8388607;
+ return 4194303;
}
function getTypeWithFacts(type, include) {
return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
@@ -31096,6 +31358,9 @@ var ts;
return f(type) ? type : neverType;
}
function mapType(type, mapper, noReductions) {
+ if (type.flags & 16384) {
+ return type;
+ }
if (!(type.flags & 131072)) {
return mapper(type);
}
@@ -31819,20 +32084,19 @@ var ts;
!(getFalsyFlags(checkExpression(declaration.initializer)) & 4096);
return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType;
}
- function isApparentTypePosition(node) {
+ function isConstraintPosition(node) {
var parent = node.parent;
return parent.kind === 183 ||
parent.kind === 185 && parent.expression === node ||
parent.kind === 184 && parent.expression === node ||
- parent.kind === 207 ||
parent.kind === 180 && parent.name === node && !!parent.initializer;
}
function typeHasNullableConstraint(type) {
return type.flags & 7372800 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288);
}
- function getApparentTypeForLocation(type, node) {
- if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) {
- return mapType(getWidenedType(type), getApparentType);
+ function getConstraintForLocation(type, node) {
+ if (isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
+ return mapType(getWidenedType(type), getBaseConstraintOrType);
}
return type;
}
@@ -31895,7 +32159,7 @@ var ts;
checkCollisionWithCapturedThisVariable(node, node);
checkCollisionWithCapturedNewTargetVariable(node, node);
checkNestedBlockScopedBinding(node, symbol);
- var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node);
+ var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
var assignmentKind = ts.getAssignmentTargetKind(node);
if (assignmentKind) {
if (!(localOrExportSymbol.flags & 3)) {
@@ -32530,7 +32794,7 @@ var ts;
}
function getContextualTypeForChildJsxExpression(node) {
var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined;
}
function getContextualTypeForJsxExpression(node) {
@@ -32656,20 +32920,14 @@ var ts;
return anyType;
}
var isJs = ts.isInJavaScriptFile(node);
- return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes);
+ return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); });
}
- function getJsxSignaturesParameterTypes(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, false);
- }
- function getJsxSignaturesParameterTypesJs(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, true);
- }
- function getJsxSignaturesParameterTypesInternal(valueType, isJs) {
+ function getJsxSignaturesParameterTypes(valueType, isJs, context) {
if (valueType.flags & 2) {
return anyType;
}
else if (valueType.flags & 32) {
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = valueType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -32692,21 +32950,21 @@ var ts;
return unknownType;
}
}
- return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0);
+ return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0);
}
- function getJsxPropsTypeFromCallSignature(sig) {
+ function getJsxPropsTypeFromCallSignature(sig, context) {
var propsType = getTypeOfFirstParameterOfSignature(sig);
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
propsType = intersectTypes(intrinsicAttribs, propsType);
}
return propsType;
}
- function getJsxPropsTypeFromClassType(hostClassType, isJs) {
+ function getJsxPropsTypeFromClassType(hostClassType, isJs, context) {
if (isTypeAny(hostClassType)) {
return hostClassType;
}
- var propsName = getJsxElementPropertiesName();
+ var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context));
if (propsName === undefined) {
return anyType;
}
@@ -32723,14 +32981,14 @@ var ts;
}
else {
var apparentAttributesType = attributesType;
- var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes);
+ var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
if (intrinsicClassAttribs !== unknownType) {
var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
apparentAttributesType = intersectTypes(typeParams
? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs))
: intrinsicClassAttribs, apparentAttributesType);
}
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
}
@@ -32738,18 +32996,12 @@ var ts;
}
}
}
- function getJsxPropsTypeFromConstructSignatureJs(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, true);
- }
- function getJsxPropsTypeFromConstructSignature(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, false);
- }
- function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) {
+ function getJsxPropsTypeFromConstructSignature(sig, isJs, context) {
var hostClassType = getReturnTypeOfSignature(sig);
if (hostClassType) {
- return getJsxPropsTypeFromClassType(hostClassType, isJs);
+ return getJsxPropsTypeFromClassType(hostClassType, isJs, context);
}
- return getJsxPropsTypeFromCallSignature(sig);
+ return getJsxPropsTypeFromCallSignature(sig, context);
}
function getContextualCallSignature(type, node) {
var signatures = getSignaturesOfType(type, 0);
@@ -32984,9 +33236,13 @@ var ts;
}
typeFlags |= type.flags;
var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined;
- var prop = nameType && isTypeUsableAsLateBoundName(nameType)
+ var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType);
+ var prop = hasLateBoundName
? createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 1024)
: createSymbol(4 | member.flags, literalName || member.escapedName);
+ if (hasLateBoundName) {
+ prop.nameType = nameType;
+ }
if (inDestructuringPattern) {
var isOptional = (memberDecl.kind === 268 && hasDefaultValue(memberDecl.initializer)) ||
(memberDecl.kind === 269 && memberDecl.objectAssignmentInitializer);
@@ -33099,7 +33355,7 @@ var ts;
}
function checkJsxSelfClosingElement(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode);
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxElement(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode);
@@ -33109,14 +33365,16 @@ var ts;
else {
checkExpression(node.closingElement.tagName);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxFragment(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode);
- if (compilerOptions.jsx === 2 && compilerOptions.jsxFactory) {
- error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory);
+ if (compilerOptions.jsx === 2 && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
+ error(node, compilerOptions.jsxFactory
+ ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
+ : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function isUnhyphenatedJsxName(name) {
return !ts.stringContains(name, "-");
@@ -33144,7 +33402,7 @@ var ts;
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
var attributeDecl = _a[_i];
var member = attributeDecl.symbol;
@@ -33231,20 +33489,19 @@ var ts;
function checkJsxAttributes(node, checkMode) {
return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
}
- function getJsxType(name) {
- var jsxType = jsxTypes.get(name);
- if (jsxType === undefined) {
- jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType);
- }
- return jsxType;
+ function getJsxType(name, location) {
+ var namespace = getJsxNamespaceAt(location);
+ var exports = namespace && getExportsOfSymbol(namespace);
+ var typeSymbol = exports && getSymbol(exports, name, 793064);
+ return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType;
}
function getIntrinsicTagSymbol(node) {
var links = getNodeLinks(node);
if (!links.resolvedSymbol) {
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
if (intrinsicElementsType !== unknownType) {
if (!ts.isIdentifier(node.tagName))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
if (intrinsicProp) {
links.jsxFlags |= 1;
@@ -33285,7 +33542,7 @@ var ts;
var signature = signatures_3[_i];
if (signature.typeParameters) {
var isJavascript = ts.isInJavaScriptFile(node);
- var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0);
+ var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 4 : 0);
var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext);
instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript));
}
@@ -33295,8 +33552,18 @@ var ts;
}
return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2);
}
- function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) {
- var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined);
+ function getJsxNamespaceAt(location) {
+ var namespaceName = getJsxNamespace(location);
+ var resolvedNamespace = resolveName(location, namespaceName, 1920, undefined, namespaceName, false);
+ if (resolvedNamespace) {
+ var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920);
+ if (candidate) {
+ return candidate;
+ }
+ }
+ return getGlobalSymbol(JsxNames.JSX, 1920, undefined);
+ }
+ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064);
var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
@@ -33313,19 +33580,11 @@ var ts;
}
return undefined;
}
- function getJsxElementPropertiesName() {
- if (!_hasComputedJsxElementPropertiesName) {
- _hasComputedJsxElementPropertiesName = true;
- _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer);
- }
- return _jsxElementPropertiesName;
+ function getJsxElementPropertiesName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
}
- function getJsxElementChildrenPropertyName() {
- if (!_hasComputedJsxElementChildrenPropertyName) {
- _hasComputedJsxElementChildrenPropertyName = true;
- _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer);
- }
- return _jsxElementChildrenPropertyName;
+ function getJsxElementChildrenPropertyName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
function getApparentTypeOfJsxPropsType(propsType) {
if (!propsType) {
@@ -33344,7 +33603,7 @@ var ts;
function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
ts.Debug.assert(!(elementType.flags & 131072));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined);
if (callSignature !== unknownSignature) {
@@ -33352,7 +33611,7 @@ var ts;
var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0]));
paramType = getApparentTypeOfJsxPropsType(paramType);
if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
paramType = intersectTypes(intrinsicAttributes, paramType);
}
@@ -33366,7 +33625,7 @@ var ts;
function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
ts.Debug.assert(!(elementType.flags & 131072));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
var candidatesOutArray = [];
getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray);
@@ -33397,7 +33656,7 @@ var ts;
if (!result) {
result = allMatchingAttributesType;
}
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
result = intersectTypes(intrinsicAttributes, result);
}
@@ -33417,7 +33676,7 @@ var ts;
return anyType;
}
else if (elementType.flags & 32) {
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = elementType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -33442,7 +33701,7 @@ var ts;
if (elementClassType) {
checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
}
- return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement));
+ return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement);
}
function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
@@ -33462,7 +33721,7 @@ var ts;
return links.resolvedJsxElementAttributesType;
}
function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) {
- return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType());
+ return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node));
}
function getAllAttributesTypeFromJsxOpeningLikeElement(node) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
@@ -33485,36 +33744,30 @@ var ts;
var prop = getPropertyOfType(attributesType, attrib.name.escapedText);
return prop || unknownSymbol;
}
- function getJsxGlobalElementClassType() {
- if (!deferredJsxElementClassType) {
- deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass);
- }
- return deferredJsxElementClassType;
+ function getJsxElementClassTypeAt(location) {
+ var type = getJsxType(JsxNames.ElementClass, location);
+ if (type === unknownType)
+ return undefined;
+ return type;
}
- function getJsxGlobalElementType() {
- if (!deferredJsxElementType) {
- deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element);
- }
- return deferredJsxElementType;
+ function getJsxElementTypeAt(location) {
+ return getJsxType(JsxNames.Element, location);
}
- function getJsxGlobalStatelessElementType() {
- if (!deferredJsxStatelessElementType) {
- var jsxElementType = getJsxGlobalElementType();
- if (jsxElementType) {
- deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]);
- }
+ function getJsxStatelessElementTypeAt(location) {
+ var jsxElementType = getJsxElementTypeAt(location);
+ if (jsxElementType) {
+ return getUnionType([jsxElementType, nullType]);
}
- return deferredJsxStatelessElementType;
}
- function getJsxIntrinsicTagNames() {
- var intrinsics = getJsxType(JsxNames.IntrinsicElements);
+ function getJsxIntrinsicTagNamesAt(location) {
+ var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
}
function checkJsxPreconditions(errorNode) {
if ((compilerOptions.jsx || 0) === 0) {
error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
}
- if (getJsxGlobalElementType() === undefined) {
+ if (getJsxElementTypeAt(errorNode) === undefined) {
if (noImplicitAny) {
error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
}
@@ -33527,7 +33780,7 @@ var ts;
}
checkJsxPreconditions(node);
var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined;
- var reactNamespace = getJsxNamespace();
+ var reactNamespace = getJsxNamespace(node);
var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
var reactSym = resolveName(reactLocation, reactNamespace, 107455, reactRefErr, reactNamespace, true);
if (reactSym) {
@@ -33569,7 +33822,7 @@ var ts;
getCustomJsxElementAttributesType(openingLikeElement, false);
var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode);
if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || getPropertiesOfType(sourceAttributesType).length > 0)) {
- error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName()));
+ error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement))));
}
else {
var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement);
@@ -33739,7 +33992,7 @@ var ts;
return unknownType;
}
}
- propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node);
+ propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
}
if (node.kind !== 183 ||
assignmentKind === 1 ||
@@ -33849,6 +34102,10 @@ var ts;
});
return result && ts.symbolName(result);
}
+ function getSuggestionForNonexistentModule(name, targetModule) {
+ var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475);
+ return suggestion && ts.symbolName(suggestion);
+ }
function getSpellingSuggestionForName(name, symbols, meaning) {
var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
var bestDistance = Math.floor(name.length * 0.4) + 1;
@@ -34189,12 +34446,12 @@ var ts;
return undefined;
}
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
- var context = createInferenceContext(signature, 1, compareTypes);
+ var context = createInferenceContext(signature.typeParameters, signature, 1, compareTypes);
forEachMatchingParameterType(contextualSignature, signature, function (source, target) {
inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target);
});
if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4);
+ inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8);
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration));
}
@@ -34223,7 +34480,7 @@ var ts;
getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) :
instantiatedType;
var inferenceTargetType = getReturnTypeOfSignature(signature);
- inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4);
+ inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8);
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -34634,7 +34891,7 @@ var ts;
}
var candidate = void 0;
var inferenceContext = originalCandidate.typeParameters ?
- createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) :
+ createInferenceContext(originalCandidate.typeParameters, originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) :
undefined;
while (true) {
candidate = originalCandidate;
@@ -35089,7 +35346,7 @@ var ts;
return false;
}
if (!ts.isIdentifier(node.expression))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined, true);
if (!resolvedRequire) {
return true;
@@ -37950,7 +38207,7 @@ var ts;
var symbol = getSymbolOfNode(node);
if (symbol.flags & 1) {
if (!ts.isIdentifier(node.name))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined, false);
if (localDeclarationSymbol &&
localDeclarationSymbol !== symbol &&
@@ -38883,7 +39140,7 @@ var ts;
var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
if (prop && baseProp) {
- var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); };
+ var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); };
if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, undefined, rootChain)) {
issuedMemberError = true;
}
@@ -39435,7 +39692,10 @@ var ts;
}
function checkExternalImportOrExportDeclaration(node) {
var moduleName = ts.getExternalModuleName(node);
- if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) {
+ if (ts.nodeIsMissing(moduleName)) {
+ return false;
+ }
+ if (!ts.isStringLiteral(moduleName)) {
error(moduleName, ts.Diagnostics.String_literal_expected);
return false;
}
@@ -39446,7 +39706,7 @@ var ts;
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
return false;
}
- if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) {
+ if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
if (!isTopLevelInExternalModuleAugmentation(node)) {
error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
return false;
@@ -40820,7 +41080,7 @@ var ts;
return !!(symbol && ts.getCheckFlags(symbol) & 1024);
},
writeLiteralConstValue: writeLiteralConstValue,
- getJsxFactoryEntity: function () { return _jsxFactoryEntity; }
+ getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }
};
function getTypeReferenceDirectivesForEntityName(node) {
if (!fileToDirective) {
@@ -42317,9 +42577,15 @@ var ts;
: node;
}
ts.updateQualifiedName = updateQualifiedName;
+ function parenthesizeForComputedName(expression) {
+ return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26) ||
+ expression.kind === 296 ?
+ createParen(expression) :
+ expression;
+ }
function createComputedPropertyName(expression) {
var node = createSynthesizedNode(146);
- node.expression = expression;
+ node.expression = parenthesizeForComputedName(expression);
return node;
}
ts.createComputedPropertyName = createComputedPropertyName;
@@ -44102,7 +44368,7 @@ var ts;
var node = createSynthesizedNode(268);
node.name = asName(name);
node.questionToken = undefined;
- node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
+ node.initializer = ts.parenthesizeExpressionForList(initializer);
return node;
}
ts.createPropertyAssignment = createPropertyAssignment;
@@ -44210,6 +44476,12 @@ var ts;
updated.imports = node.imports;
if (node.moduleAugmentations !== undefined)
updated.moduleAugmentations = node.moduleAugmentations;
+ if (node.pragmas !== undefined)
+ updated.pragmas = node.pragmas;
+ if (node.localJsxFactory !== undefined)
+ updated.localJsxFactory = node.localJsxFactory;
+ if (node.localJsxNamespace !== undefined)
+ updated.localJsxNamespace = node.localJsxNamespace;
return updateNode(updated, node);
}
return node;
@@ -46638,7 +46910,7 @@ var ts;
var uniqueExports = ts.createMap();
var exportedNames;
var hasExportDefault = false;
- var exportEquals = undefined;
+ var exportEquals;
var hasExportStarsToExportValues = false;
var hasImportStarOrImportDefault = false;
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
@@ -47653,7 +47925,7 @@ var ts;
ts.setEmitFlags(propertyName, 1536 | 48);
var localName = ts.getMutableClone(name);
ts.setEmitFlags(localName, 1536);
- return ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)));
+ return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536));
}
function getInitializedProperties(node, isStatic) {
return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty);
@@ -49860,14 +50132,14 @@ var ts;
objectProperties = ts.createAssignHelper(context, segments);
}
}
- var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
return element;
}
function visitJsxOpeningFragment(node, children, isChild, location) {
- var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
@@ -50906,11 +51178,11 @@ var ts;
function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
initializer = ts.visitNode(initializer, visitor, ts.isExpression);
var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
- ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer))), parameter))
- ]), parameter), 1 | 32 | 384));
+ ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer) | 1536)), parameter), 1536))
+ ]), parameter), 1 | 32 | 384 | 1536));
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
- ts.setEmitFlags(statement, 384 | 32 | 1048576);
+ ts.setEmitFlags(statement, 384 | 32 | 1048576 | 1536);
statements.push(statement);
}
function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
@@ -54836,12 +55108,12 @@ var ts;
var importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
- text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}"
+ text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
var importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
- text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}"
+ text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
};
})(ts || (ts = {}));
var ts;
@@ -56220,8 +56492,8 @@ var ts;
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = ts.createMap();
}
- for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) {
- var directive = typeReferenceDirectives_1[_i];
+ for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
+ var directive = typeReferenceDirectives_2[_i];
if (!usedTypeDirectiveReferences.has(directive)) {
usedTypeDirectiveReferences.set(directive, directive);
}
@@ -56499,7 +56771,12 @@ var ts;
"?");
}
write(": ");
- emitType(node.type);
+ if (node.type) {
+ emitType(node.type);
+ }
+ else {
+ write("any");
+ }
write(";");
writeLine();
decreaseIndent();
@@ -59097,7 +59374,7 @@ var ts;
else {
emitTypeAnnotation(node.type);
}
- emitInitializer(node.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);
}
function emitDecorator(decorator) {
writePunctuation("@");
@@ -59116,8 +59393,9 @@ var ts;
emitModifiers(node, node.modifiers);
emit(node.name);
emitIfPresent(node.questionToken);
+ emitIfPresent(node.exclamationToken);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
writeSemicolon();
}
function emitMethodSignature(node) {
@@ -59356,7 +59634,7 @@ var ts;
writeSpace();
}
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
function emitArrayLiteralExpression(node) {
var elements = node.elements;
@@ -59390,7 +59668,10 @@ var ts;
emitExpression(node.expression);
increaseIndentIf(indentBeforeDot);
var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression);
- writePunctuation(shouldEmitDotDot ? ".." : ".");
+ if (shouldEmitDotDot) {
+ writePunctuation(".");
+ }
+ emitTokenWithComment(23, node.expression.end, writePunctuation, node);
increaseIndentIf(indentAfterDot);
emit(node.name);
decreaseIndentIf(indentBeforeDot, indentAfterDot);
@@ -59411,9 +59692,9 @@ var ts;
}
function emitElementAccessExpression(node) {
emitExpression(node.expression);
- writePunctuation("[");
+ var openPos = emitTokenWithComment(21, node.expression.end, writePunctuation, node);
emitExpression(node.argumentExpression);
- writePunctuation("]");
+ emitTokenWithComment(22, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node);
}
function emitCallExpression(node) {
emitExpression(node.expression);
@@ -59421,7 +59702,7 @@ var ts;
emitExpressionList(node, node.arguments, 1296);
}
function emitNewExpression(node) {
- writeKeyword("new");
+ emitTokenWithComment(94, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
emitTypeArguments(node, node.typeArguments);
@@ -59439,9 +59720,9 @@ var ts;
emitExpression(node.expression);
}
function emitParenthesizedExpression(node) {
- writePunctuation("(");
+ var openParenPos = emitTokenWithComment(19, node.pos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
}
function emitFunctionExpression(node) {
emitFunctionDeclarationOrExpression(node);
@@ -59459,22 +59740,22 @@ var ts;
emit(node.equalsGreaterThanToken);
}
function emitDeleteExpression(node) {
- writeKeyword("delete");
+ emitTokenWithComment(80, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitTypeOfExpression(node) {
- writeKeyword("typeof");
+ emitTokenWithComment(103, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitVoidExpression(node) {
- writeKeyword("void");
+ emitTokenWithComment(105, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitAwaitExpression(node) {
- writeKeyword("await");
+ emitTokenWithComment(121, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
@@ -59530,7 +59811,7 @@ var ts;
emitList(node, node.templateSpans, 131072);
}
function emitYieldExpression(node) {
- writeKeyword("yield");
+ emitTokenWithComment(116, node.pos, writeKeyword, node);
emit(node.asteriskToken);
emitExpressionWithLeadingSpace(node.expression);
}
@@ -59568,16 +59849,13 @@ var ts;
emit(node.literal);
}
function emitBlock(node) {
- writeToken(17, node.pos, writePunctuation, node);
emitBlockStatements(node, !node.multiLine && isEmptyBlock(node));
- increaseIndent();
- emitLeadingCommentsOfPosition(node.statements.end);
- decreaseIndent();
- writeToken(18, node.statements.end, writePunctuation, node);
}
function emitBlockStatements(node, forceSingleLine) {
+ emitTokenWithComment(17, node.pos, writePunctuation, node);
var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65;
emitList(node, node.statements, format);
+ emitTokenWithComment(18, node.statements.end, writePunctuation, node, !!(format & 1));
}
function emitVariableStatement(node) {
emitModifiers(node, node.modifiers);
@@ -59592,15 +59870,15 @@ var ts;
writeSemicolon();
}
function emitIfStatement(node) {
- var openParenPos = writeToken(90, node.pos, writeKeyword, node);
+ var openParenPos = emitTokenWithComment(90, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19, openParenPos, writePunctuation, node);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20, node.expression.end, writePunctuation, node);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.thenStatement);
if (node.elseStatement) {
writeLineOrSpace(node);
- writeToken(82, node.thenStatement.end, writeKeyword, node);
+ emitTokenWithComment(82, node.thenStatement.end, writeKeyword, node);
if (node.elseStatement.kind === 215) {
writeSpace();
emit(node.elseStatement);
@@ -59610,8 +59888,15 @@ var ts;
}
}
}
+ function emitWhileClause(node, startPos) {
+ var openParenPos = emitTokenWithComment(106, startPos, writeKeyword, node);
+ writeSpace();
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
+ emitExpression(node.expression);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
+ }
function emitDoStatement(node) {
- writeKeyword("do");
+ emitTokenWithComment(81, node.pos, writeKeyword, node);
emitEmbeddedStatement(node, node.statement);
if (ts.isBlock(node.statement)) {
writeSpace();
@@ -59619,55 +59904,48 @@ var ts;
else {
writeLineOrSpace(node);
}
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(");");
+ emitWhileClause(node, node.statement.end);
+ writePunctuation(";");
}
function emitWhileStatement(node) {
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(")");
+ emitWhileClause(node, node.pos);
emitEmbeddedStatement(node, node.statement);
}
function emitForStatement(node) {
- var openParenPos = writeToken(88, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19, openParenPos, writePunctuation, node);
+ var pos = emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
- writeSemicolon();
+ pos = emitTokenWithComment(25, node.initializer ? node.initializer.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.condition);
- writeSemicolon();
+ pos = emitTokenWithComment(25, node.condition ? node.condition.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.incrementor);
- writePunctuation(")");
+ emitTokenWithComment(20, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForInStatement(node) {
- var openParenPos = writeToken(88, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19, openParenPos, writePunctuation);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("in");
+ emitTokenWithComment(92, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20, node.expression.end, writePunctuation);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForOfStatement(node) {
- var openParenPos = writeToken(88, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88, node.pos, writeKeyword, node);
writeSpace();
emitWithTrailingSpace(node.awaitModifier);
- writeToken(19, openParenPos, writePunctuation);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("of");
+ emitTokenWithComment(144, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20, node.expression.end, writePunctuation);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForBinding(node) {
@@ -59681,22 +59959,34 @@ var ts;
}
}
function emitContinueStatement(node) {
- writeToken(77, node.pos, writeKeyword);
+ emitTokenWithComment(77, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
function emitBreakStatement(node) {
- writeToken(72, node.pos, writeKeyword);
+ emitTokenWithComment(72, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
- function emitTokenWithComment(token, pos, writer, contextNode) {
+ function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
var node = contextNode && ts.getParseTreeNode(contextNode);
- if (node && node.kind === contextNode.kind) {
+ var isSimilarNode = node && node.kind === contextNode.kind;
+ var startPos = pos;
+ if (isSimilarNode) {
pos = ts.skipTrivia(currentSourceFile.text, pos);
}
- pos = writeToken(token, pos, writer, contextNode);
- if (node && node.kind === contextNode.kind) {
+ if (emitLeadingCommentsOfPosition && isSimilarNode) {
+ var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
+ if (needsIndent) {
+ increaseIndent();
+ }
+ emitLeadingCommentsOfPosition(startPos);
+ if (needsIndent) {
+ decreaseIndent();
+ }
+ }
+ pos = writeTokenText(token, writer, pos);
+ if (emitTrailingCommentsOfPosition && isSimilarNode) {
emitTrailingCommentsOfPosition(pos, true);
}
return pos;
@@ -59707,35 +59997,35 @@ var ts;
writeSemicolon();
}
function emitWithStatement(node) {
- writeKeyword("with");
+ var openParenPos = emitTokenWithComment(107, node.pos, writeKeyword, node);
writeSpace();
- writePunctuation("(");
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitSwitchStatement(node) {
- var openParenPos = writeToken(98, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(98, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19, openParenPos, writePunctuation);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20, node.expression.end, writePunctuation);
+ emitTokenWithComment(20, node.expression.end, writePunctuation, node);
writeSpace();
emit(node.caseBlock);
}
function emitLabeledStatement(node) {
emit(node.label);
- writePunctuation(":");
+ emitTokenWithComment(56, node.label.end, writePunctuation, node);
writeSpace();
emit(node.statement);
}
function emitThrowStatement(node) {
- writeKeyword("throw");
+ emitTokenWithComment(100, node.pos, writeKeyword, node);
emitExpressionWithLeadingSpace(node.expression);
writeSemicolon();
}
function emitTryStatement(node) {
- writeKeyword("try");
+ emitTokenWithComment(102, node.pos, writeKeyword, node);
writeSpace();
emit(node.tryBlock);
if (node.catchClause) {
@@ -59744,7 +60034,7 @@ var ts;
}
if (node.finallyBlock) {
writeLineOrSpace(node);
- writeKeyword("finally");
+ emitTokenWithComment(87, (node.catchClause || node.tryBlock).end, writeKeyword, node);
writeSpace();
emit(node.finallyBlock);
}
@@ -59756,7 +60046,7 @@ var ts;
function emitVariableDeclaration(node) {
emit(node.name);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
}
function emitVariableDeclarationList(node) {
writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var");
@@ -59950,23 +60240,21 @@ var ts;
}
function emitModuleBlock(node) {
pushNameGenerationScope(node);
- writePunctuation("{");
emitBlockStatements(node, isEmptyBlock(node));
- writePunctuation("}");
popNameGenerationScope(node);
}
function emitCaseBlock(node) {
- writeToken(17, node.pos, writePunctuation);
+ emitTokenWithComment(17, node.pos, writePunctuation, node);
emitList(node, node.clauses, 65);
- writeToken(18, node.clauses.end, writePunctuation);
+ emitTokenWithComment(18, node.clauses.end, writePunctuation, node, true);
}
function emitImportEqualsDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSpace();
- writePunctuation("=");
+ emitTokenWithComment(58, node.name.end, writePunctuation, node);
writeSpace();
emitModuleReference(node.moduleReference);
writeSemicolon();
@@ -59981,12 +60269,12 @@ var ts;
}
function emitImportDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
if (node.importClause) {
emit(node.importClause);
writeSpace();
- writeKeyword("from");
+ emitTokenWithComment(142, node.importClause.end, writeKeyword, node);
writeSpace();
}
emitExpression(node.moduleSpecifier);
@@ -59995,15 +60283,15 @@ var ts;
function emitImportClause(node) {
emit(node.name);
if (node.name && node.namedBindings) {
- writePunctuation(",");
+ emitTokenWithComment(26, node.name.end, writePunctuation, node);
writeSpace();
}
emit(node.namedBindings);
}
function emitNamespaceImport(node) {
- writePunctuation("*");
+ var asPos = emitTokenWithComment(39, node.pos, writePunctuation, node);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118, asPos, writeKeyword, node);
writeSpace();
emit(node.name);
}
@@ -60014,41 +60302,42 @@ var ts;
emitImportOrExportSpecifier(node);
}
function emitExportAssignment(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node);
writeSpace();
if (node.isExportEquals) {
- writeOperator("=");
+ emitTokenWithComment(58, nextPos, writeOperator, node);
}
else {
- writeKeyword("default");
+ emitTokenWithComment(79, nextPos, writeKeyword, node);
}
writeSpace();
emitExpression(node.expression);
writeSemicolon();
}
function emitExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node);
writeSpace();
if (node.exportClause) {
emit(node.exportClause);
}
else {
- writePunctuation("*");
+ nextPos = emitTokenWithComment(39, nextPos, writePunctuation, node);
}
if (node.moduleSpecifier) {
writeSpace();
- writeKeyword("from");
+ var fromPos = node.exportClause ? node.exportClause.end : nextPos;
+ emitTokenWithComment(142, fromPos, writeKeyword, node);
writeSpace();
emitExpression(node.moduleSpecifier);
}
writeSemicolon();
}
function emitNamespaceExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84, node.pos, writeKeyword, node);
writeSpace();
- writeKeyword("as");
+ nextPos = emitTokenWithComment(118, nextPos, writeKeyword, node);
writeSpace();
- writeKeyword("namespace");
+ nextPos = emitTokenWithComment(130, nextPos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSemicolon();
@@ -60068,7 +60357,7 @@ var ts;
if (node.propertyName) {
emit(node.propertyName);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118, node.propertyName.end, writeKeyword, node);
writeSpace();
}
emit(node.name);
@@ -60149,30 +60438,29 @@ var ts;
}
}
function emitCaseClause(node) {
- writeKeyword("case");
+ emitTokenWithComment(73, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
}
function emitDefaultClause(node) {
- writeKeyword("default");
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ var pos = emitTokenWithComment(79, node.pos, writeKeyword, node);
+ emitCaseOrDefaultClauseRest(node, node.statements, pos);
}
- function emitCaseOrDefaultClauseStatements(parentNode, statements) {
+ function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
var emitAsSingleStatement = statements.length === 1 &&
(ts.nodeIsSynthesized(parentNode) ||
ts.nodeIsSynthesized(statements[0]) ||
ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
- if (statements.length > 0) {
- emitTrailingCommentsOfPosition(statements.pos);
- }
var format = 81985;
if (emitAsSingleStatement) {
+ writeToken(56, colonPos, writePunctuation, parentNode);
writeSpace();
format &= ~(1 | 64);
}
+ else {
+ emitTokenWithComment(56, colonPos, writePunctuation, parentNode);
+ }
emitList(parentNode, statements, format);
}
function emitHeritageClause(node) {
@@ -60182,12 +60470,12 @@ var ts;
emitList(node, node.types, 272);
}
function emitCatchClause(node) {
- var openParenPos = writeToken(74, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(74, node.pos, writeKeyword, node);
writeSpace();
if (node.variableDeclaration) {
- writeToken(19, openParenPos, writePunctuation);
+ emitTokenWithComment(19, openParenPos, writePunctuation, node);
emit(node.variableDeclaration);
- writeToken(20, node.variableDeclaration.end, writePunctuation);
+ emitTokenWithComment(20, node.variableDeclaration.end, writePunctuation, node);
writeSpace();
}
emit(node.block);
@@ -60220,7 +60508,7 @@ var ts;
}
function emitEnumMember(node) {
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
function emitSourceFile(node) {
writeLine();
@@ -60322,10 +60610,10 @@ var ts;
emit(node);
}
}
- function emitInitializer(node) {
+ function emitInitializer(node, equalCommentStartPos, container) {
if (node) {
writeSpace();
- writeOperator("=");
+ emitTokenWithComment(58, equalCommentStartPos, writeOperator, container);
writeSpace();
emitExpression(node);
}
@@ -60450,6 +60738,9 @@ var ts;
}
if (format & 7680) {
writePunctuation(getOpeningBracket(format));
+ if (isEmpty) {
+ emitTrailingCommentsOfPosition(children.pos, true);
+ }
}
if (onBeforeEmitNodeArray) {
onBeforeEmitNodeArray(children);
@@ -60533,6 +60824,9 @@ var ts;
onAfterEmitNodeArray(children);
}
if (format & 7680) {
+ if (isEmpty) {
+ emitLeadingCommentsOfPosition(children.end);
+ }
writePunctuation(getClosingBracket(format));
}
}
@@ -61167,8 +61461,7 @@ var ts;
}
ts.formatDiagnostics = formatDiagnostics;
function formatDiagnostic(diagnostic, host) {
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
+ var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
@@ -61192,8 +61485,9 @@ var ts;
var ellipsis = "...";
function getCategoryFormat(category) {
switch (category) {
- case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
+ case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
+ case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
}
}
@@ -61223,8 +61517,8 @@ var ts;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
- context += host.getNewLine();
for (var i = firstLine; i <= lastLine; i++) {
+ context += host.getNewLine();
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
i = lastLine - 1;
@@ -61258,9 +61552,7 @@ var ts;
output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
output += " - ";
}
- var categoryColor = getCategoryFormat(diagnostic.category);
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- output += formatColorAndReset(category, categoryColor);
+ output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file) {
@@ -62876,6 +63168,13 @@ var ts;
category: ts.Diagnostics.Command_line_Options,
description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
},
+ {
+ name: "preserveWatchOutput",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
+ },
{
name: "watch",
shortName: "w",
@@ -62953,9 +63252,10 @@ var ts;
"es2017.string": "lib.es2017.string.d.ts",
"es2017.intl": "lib.es2017.intl.d.ts",
"es2017.typedarrays": "lib.es2017.typedarrays.d.ts",
+ "es2018.promise": "lib.es2018.promise.d.ts",
+ "es2018.regexp": "lib.es2018.regexp.d.ts",
"esnext.array": "lib.esnext.array.d.ts",
"esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
- "esnext.promise": "lib.esnext.promise.d.ts",
}),
},
showInSimplifiedHelpView: true,
@@ -64971,16 +65271,13 @@ var ts;
}
ts.getTargetLabel = getTargetLabel;
function isJumpStatementTarget(node) {
- return node.kind === 71 &&
- (node.parent.kind === 222 || node.parent.kind === 221) &&
- node.parent.label === node;
+ return node.kind === 71 && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node;
}
ts.isJumpStatementTarget = isJumpStatementTarget;
function isLabelOfLabeledStatement(node) {
- return node.kind === 71 &&
- node.parent.kind === 226 &&
- node.parent.label === node;
+ return node.kind === 71 && ts.isLabeledStatement(node.parent) && node.parent.label === node;
}
+ ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement;
function isLabelName(node) {
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
@@ -65319,11 +65616,7 @@ var ts;
}
ts.findChildOfKind = findChildOfKind;
function findContainingList(node) {
- var syntaxList = ts.forEach(node.parent.getChildren(), function (c) {
- if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) {
- return c;
- }
- });
+ var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); });
ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node));
return syntaxList;
}
@@ -65970,7 +66263,7 @@ var ts;
}
function suppressTrailing(node) {
ts.addEmitFlags(node, 1024);
- var lastChild = undefined;
+ var lastChild;
ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) {
if (children.length) {
lastChild = ts.last(children);
@@ -66155,16 +66448,15 @@ var ts;
return textSpan(node);
}
if (node.kind === 198) {
- var binaryExpression = node;
- if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) {
- return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left);
+ var _a = node, left = _a.left, operatorToken = _a.operatorToken;
+ if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
+ return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left);
}
- if (binaryExpression.operatorToken.kind === 58 &&
- ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) {
+ if (operatorToken.kind === 58 && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
return textSpan(node);
}
- if (binaryExpression.operatorToken.kind === 26) {
- return spanInNode(binaryExpression.left);
+ if (operatorToken.kind === 26) {
+ return spanInNode(left);
}
}
if (ts.isExpressionNode(node)) {
@@ -66188,40 +66480,43 @@ var ts;
break;
}
}
- if (node.parent.kind === 268 &&
- node.parent.name === node &&
- !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
- return spanInNode(node.parent.initializer);
- }
- if (node.parent.kind === 188 && node.parent.type === node) {
- return spanInNextNode(node.parent.type);
- }
- if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
- return spanInPreviousNode(node);
- }
- if ((node.parent.kind === 230 ||
- node.parent.kind === 148)) {
- var paramOrVarDecl = node.parent;
- if (paramOrVarDecl.initializer === node ||
- paramOrVarDecl.type === node ||
- ts.isAssignmentOperator(node.kind)) {
- return spanInPreviousNode(node);
+ switch (node.parent.kind) {
+ case 268:
+ if (node.parent.name === node &&
+ !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
+ return spanInNode(node.parent.initializer);
+ }
+ break;
+ case 188:
+ if (node.parent.type === node) {
+ return spanInNextNode(node.parent.type);
+ }
+ break;
+ case 230:
+ case 148: {
+ var _b = node.parent, initializer = _b.initializer, type = _b.type;
+ if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) {
+ return spanInPreviousNode(node);
+ }
+ break;
}
- }
- if (node.parent.kind === 198) {
- var binaryExpression = node.parent;
- if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) &&
- (binaryExpression.right === node ||
- binaryExpression.operatorToken === node)) {
- return spanInPreviousNode(node);
+ case 198: {
+ var left = node.parent.left;
+ if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
+ return spanInPreviousNode(node);
+ }
+ break;
}
+ default:
+ if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
+ return spanInPreviousNode(node);
+ }
}
return spanInNode(node.parent);
}
}
function textSpanFromVariableDeclaration(variableDeclaration) {
- if (variableDeclaration.parent.kind === 231 &&
- variableDeclaration.parent.declarations[0] === variableDeclaration) {
+ if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
}
else {
@@ -66240,7 +66535,7 @@ var ts;
variableDeclaration.parent.parent.kind === 220) {
return textSpanFromVariableDeclaration(variableDeclaration);
}
- if (variableDeclaration.parent.kind === 231 &&
+ if (ts.isVariableDeclarationList(variableDeclaration.parent) &&
variableDeclaration.parent.declarations[0] !== variableDeclaration) {
return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
}
@@ -66616,7 +66911,7 @@ var ts;
case 13:
return 4;
default:
- throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
+ return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
}
}
return lastOnTemplateStack === 14 ? 6 : undefined;
@@ -66709,7 +67004,7 @@ var ts;
case 0:
return { prefix: "" };
default:
- throw ts.Debug.assertNever(lexState);
+ return ts.Debug.assertNever(lexState);
}
}
function isBinaryExpressionOperatorToken(token) {
@@ -67636,7 +67931,7 @@ var ts;
case 3:
return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag));
default:
- throw ts.Debug.assertNever(completionData);
+ return ts.Debug.assertNever(completionData);
}
}
Completions.getCompletionsAtPosition = getCompletionsAtPosition;
@@ -67673,7 +67968,7 @@ var ts;
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
}
function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) {
- var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
+ var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
if (sourceFile.languageVariant === 1 && location && location.parent && ts.isJsxClosingElement(location.parent)) {
var tagName = location.parent.parent.openingElement.tagName;
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false,
@@ -67699,7 +67994,7 @@ var ts;
if (keywordFilters !== 0 || !isMemberCompletion) {
ts.addRange(entries, getKeywordCompletions(keywordFilters));
}
- return { isGlobalCompletion: completionKind === 1, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
+ return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
}
function isMemberCompletionKind(kind) {
switch (kind) {
@@ -68071,6 +68366,7 @@ var ts;
var insideComment = ts.isInComment(sourceFile, position, currentToken);
log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
var insideJsDocTagTypeExpression = false;
+ var isInSnippetScope = false;
if (insideComment) {
if (ts.hasDocComment(sourceFile, position)) {
if (sourceFile.text.charCodeAt(position - 1) === 64) {
@@ -68204,7 +68500,7 @@ var ts;
getTypeScriptMemberSymbols();
}
else if (isRightOfOpenTag) {
- var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNames(), "getJsxIntrinsicTagNames() should all be defined");
+ var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
if (tryGetGlobalSymbols()) {
symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 2097152)); }));
}
@@ -68228,7 +68524,7 @@ var ts;
}
log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart));
var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, position, sourceFile, typeChecker);
- return { kind: 0, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
+ return { kind: 0, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
case 287:
@@ -68320,7 +68616,7 @@ var ts;
if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) {
keywordFilters = 3;
}
- completionKind = 5;
+ completionKind = 1;
isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
if (previousToken !== contextToken) {
ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
@@ -68329,9 +68625,7 @@ var ts;
previousToken.getStart() :
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
- if (isGlobalCompletionScope(scopeNode)) {
- completionKind = 1;
- }
+ isInSnippetScope = isSnippetScope(scopeNode);
var symbolMeanings = 793064 | 107455 | 1920 | 2097152;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
if (options.includeInsertTextCompletions && scopeNode.kind !== 272) {
@@ -68350,7 +68644,7 @@ var ts;
filterGlobalCompletion(symbols);
return true;
}
- function isGlobalCompletionScope(scopeNode) {
+ function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
case 272:
case 200:
@@ -68563,7 +68857,7 @@ var ts;
isNewIdentifierLocation = false;
var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
if (!ts.isVariableLike(rootDeclaration))
- throw ts.Debug.fail("Root declaration is not variable-like.");
+ return ts.Debug.fail("Root declaration is not variable-like.");
var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 220;
if (!canGetType && rootDeclaration.kind === 148) {
if (ts.isExpression(rootDeclaration.parent)) {
@@ -68934,7 +69228,7 @@ var ts;
}
else {
var name = ts.getNameOfDeclaration(m);
- existingName = ts.getEscapedTextOfIdentifierOrLiteral(name);
+ existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
existingMemberNames.set(existingName, true);
}
@@ -69018,9 +69312,9 @@ var ts;
case 0:
return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
case 2:
- case 5:
case 1:
return name.charCodeAt(0) === 32 ? undefined : { name: name, needsConvertPropertyAccess: true };
+ case 5:
case 4:
return validIdentiferResult;
default:
@@ -69182,30 +69476,17 @@ var ts;
}
function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken);
- return referenceEntries && convertReferencedSymbols(referenceEntries);
- }
- function convertReferencedSymbols(referenceEntries) {
- var fileNameToDocumentHighlights = ts.createMap();
- for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
- var entry = referenceEntries_1[_i];
- var _a = ts.FindAllReferences.toHighlightSpan(entry), fileName = _a.fileName, span_12 = _a.span;
- var highlightSpans = fileNameToDocumentHighlights.get(fileName);
- if (!highlightSpans) {
- fileNameToDocumentHighlights.set(fileName, highlightSpans = []);
- }
- highlightSpans.push(span_12);
- }
- return ts.arrayFrom(fileNameToDocumentHighlights.entries(), function (_a) {
+ 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) {
var fileName = _a[0], highlightSpans = _a[1];
return ({ fileName: fileName, highlightSpans: highlightSpans });
});
}
function getSyntacticDocumentHighlights(node, sourceFile) {
var highlightSpans = getHighlightSpans(node, sourceFile);
- if (!highlightSpans || highlightSpans.length === 0) {
- return undefined;
- }
- return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
+ return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
}
function getHighlightSpans(node, sourceFile) {
switch (node.kind) {
@@ -69691,7 +69972,9 @@ var ts;
}
else if (ts.isDefaultImport(direct)) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(direct);
- addIndirectUser(sourceFileLike);
+ if (!isAvailableThroughGlobal) {
+ addIndirectUser(sourceFileLike);
+ }
directImports.push(direct);
}
else {
@@ -70122,8 +70405,8 @@ var ts;
if (parent.kind === 272) {
return parent;
}
- ts.Debug.assert(parent.kind === 238 && isAmbientModuleDeclaration(parent.parent));
- return parent.parent;
+ ts.Debug.assert(parent.kind === 238);
+ return ts.cast(parent.parent, isAmbientModuleDeclaration);
}
function isAmbientModuleDeclaration(node) {
return node.kind === 237 && node.name.kind === 9;
@@ -70143,11 +70426,12 @@ var ts;
}
FindAllReferences.nodeEntry = nodeEntry;
function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
- var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position);
+ var node = ts.getTouchingPropertyName(sourceFile, position, true);
+ var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, {});
var checker = program.getTypeChecker();
return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) {
var definition = _a.definition, references = _a.references;
- return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) };
+ return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) };
});
}
FindAllReferences.findReferencedSymbols = findReferencedSymbols;
@@ -70177,8 +70461,8 @@ var ts;
}
}
function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) {
- var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options));
- return ts.map(x, toReferenceEntry);
+ var node = ts.getTouchingPropertyName(sourceFile, position, true);
+ return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry);
}
FindAllReferences.findReferencedEntries = findReferencedEntries;
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) {
@@ -70186,46 +70470,41 @@ var ts;
return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options));
}
FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode;
- function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) {
- var node = ts.getTouchingPropertyName(sourceFile, position, true);
- return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options);
- }
function flattenEntries(referenceSymbols) {
return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
}
- function definitionToReferencedSymbolDefinitionInfo(def, checker) {
+ function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
var info = (function () {
switch (def.type) {
case "symbol": {
- var symbol = def.symbol, node_3 = def.node;
- var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
+ var symbol = def.symbol;
+ var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
var name_4 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 };
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 };
}
case "label": {
- var node_4 = def.node;
- return { node: node_4, name: node_4.text, kind: "label", displayParts: [ts.displayPart(node_4.text, ts.SymbolDisplayPartKind.text)] };
+ var node_3 = def.node;
+ return { node: node_3, name: node_3.text, kind: "label", displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
}
case "keyword": {
- var node_5 = def.node;
- var name_5 = ts.tokenToString(node_5.kind);
- return { node: node_5, name: name_5, kind: "keyword", displayParts: [{ text: name_5, kind: "keyword" }] };
+ var node_4 = def.node;
+ var name_5 = ts.tokenToString(node_4.kind);
+ return { node: node_4, name: name_5, kind: "keyword", displayParts: [{ text: name_5, kind: "keyword" }] };
}
case "this": {
- var node_6 = def.node;
- var symbol = checker.getSymbolAtLocation(node_6);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_6.getSourceFile(), ts.getContainerNode(node_6), node_6).displayParts;
- return { node: node_6, name: "this", kind: "var", displayParts: displayParts_2 };
+ var node_5 = def.node;
+ var symbol = checker.getSymbolAtLocation(node_5);
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts;
+ return { node: node_5, name: "this", kind: "var", displayParts: displayParts_2 };
}
case "string": {
- var node_7 = def.node;
- return { node: node_7, name: node_7.text, kind: "var", displayParts: [ts.displayPart(ts.getTextOfNode(node_7), ts.SymbolDisplayPartKind.stringLiteral)] };
+ var node_6 = def.node;
+ return { node: node_6, name: node_6.text, kind: "var", displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
}
+ default:
+ return ts.Debug.assertNever(def);
}
})();
- if (!info) {
- return undefined;
- }
var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts;
var sourceFile = node.getSourceFile();
return {
@@ -70238,8 +70517,10 @@ var ts;
displayParts: displayParts
};
}
- function getDefinitionKindAndDisplayParts(symbol, node, checker) {
- var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
+ function getDefinitionKindAndDisplayParts(symbol, checker, node) {
+ var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol);
+ var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node;
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
return { displayParts: displayParts, kind: symbolKind };
}
function toReferenceEntry(entry) {
@@ -70270,7 +70551,7 @@ var ts;
function implementationKindDisplayParts(node, checker) {
var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node);
if (symbol) {
- return getDefinitionKindAndDisplayParts(symbol, node, checker);
+ return getDefinitionKindAndDisplayParts(symbol, checker, node);
}
else if (node.kind === 182) {
return {
@@ -70388,23 +70669,18 @@ var ts;
ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
- return [{
- definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration },
- references: references
- }];
+ return [{ definition: { type: "symbol", symbol: symbol }, references: references }];
}
function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
if (ts.isTypeKeyword(node.kind)) {
return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken);
}
- if (ts.isLabelName(node)) {
- if (ts.isJumpStatementTarget(node)) {
- var labelDefinition = ts.getTargetLabel(node.parent, node.text);
- return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
- }
- else {
- return getLabelReferencesInNode(node.parent, node);
- }
+ if (ts.isJumpStatementTarget(node)) {
+ var labelDefinition = ts.getTargetLabel(node.parent, node.text);
+ return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
+ }
+ else if (ts.isLabelOfLabeledStatement(node)) {
+ return getLabelReferencesInNode(node.parent, node);
}
if (ts.isThis(node)) {
return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
@@ -70416,11 +70692,11 @@ var ts;
}
function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) {
symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
- var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations);
+ var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol);
var result = [];
var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result);
if (node.kind === 79) {
- addReference(node, symbol, node, state);
+ addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 }, state);
}
else {
@@ -70490,7 +70766,11 @@ var ts;
this.markSeenReExportRHS = ts.nodeSeenTracker();
this.symbolIdToReferences = [];
this.sourceFileToSeenSymbols = [];
+ this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; });
}
+ State.prototype.includesSourceFile = function (sourceFile) {
+ return this.includedSourceFiles.has(sourceFile.fileName);
+ };
State.prototype.getImportSearches = function (exportSymbol, exportInfo) {
if (!this.importTracker)
this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.checker, this.cancellationToken);
@@ -70498,20 +70778,20 @@ var ts;
};
State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) {
if (searchOptions === void 0) { searchOptions = {}; }
- var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b;
+ var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, allSearchSymbols = searchOptions.allSearchSymbols;
var escapedText = ts.escapeLeadingUnderscores(text);
var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
return {
- location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents,
+ symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents,
includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; },
};
};
- State.prototype.referenceAdder = function (searchSymbol, searchLocation) {
+ State.prototype.referenceAdder = function (searchSymbol) {
var symbolId = ts.getSymbolId(searchSymbol);
var references = this.symbolIdToReferences[symbolId];
if (!references) {
references = this.symbolIdToReferences[symbolId] = [];
- this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references });
+ this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references });
}
return function (node) { return references.push(FindAllReferences.nodeEntry(node)); };
};
@@ -70532,7 +70812,7 @@ var ts;
function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) {
var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers;
if (singleReferences.length) {
- var addRef = state.referenceAdder(exportSymbol, exportLocation);
+ var addRef = state.referenceAdder(exportSymbol);
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
addRef(singleRef);
@@ -70565,7 +70845,10 @@ var ts;
function searchForImportedSymbol(symbol, state) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- getReferencesInSourceFile(declaration.getSourceFile(), state.createSearch(declaration, symbol, 0), state);
+ var exportingFile = declaration.getSourceFile();
+ if (state.includesSourceFile(exportingFile)) {
+ getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0), state);
+ }
}
}
function searchForName(sourceFile, search, state) {
@@ -70633,6 +70916,16 @@ var ts;
}
return exposedByParent ? scope.getSourceFile() : scope;
}
+ function isSymbolReferencedInFile(definition, checker, sourceFile) {
+ var symbol = checker.getSymbolAtLocation(definition);
+ if (!symbol)
+ return true;
+ return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) {
+ var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, true), ts.isIdentifier);
+ return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol;
+ });
+ }
+ Core.isSymbolReferencedInFile = isSymbolReferencedInFile;
function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) {
if (container === void 0) { container = sourceFile; }
var positions = [];
@@ -70656,17 +70949,12 @@ var ts;
return positions;
}
function getLabelReferencesInNode(container, targetLabel) {
- var references = [];
var sourceFile = container.getSourceFile();
var labelName = targetLabel.text;
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container);
- for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) {
- var position = possiblePositions_1[_i];
+ var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) {
var node = ts.getTouchingWord(sourceFile, position, false);
- if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) {
- references.push(FindAllReferences.nodeEntry(node));
- }
- }
+ return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined;
+ });
return [{ definition: { type: "label", node: targetLabel }, references: references }];
}
function isValidReferencePosition(node, searchSymbolName) {
@@ -70685,24 +70973,15 @@ var ts;
}
}
function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) {
- var references = [];
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
+ var references = ts.flatMap(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references);
- }
+ return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) {
+ var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true);
+ return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined;
+ });
+ });
return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined;
}
- function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) {
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile);
- for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) {
- var position = possiblePositions_2[_i];
- var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true);
- if (referenceLocation.kind === kind) {
- references.push(FindAllReferences.nodeEntry(referenceLocation));
- }
- }
- }
function getReferencesInSourceFile(sourceFile, search, state) {
state.cancellationToken.throwIfCancellationRequested();
return getReferencesInContainer(sourceFile, sourceFile, search, state);
@@ -70747,7 +71026,7 @@ var ts;
}
switch (state.specialSearchKind) {
case 0:
- addReference(referenceLocation, relatedSymbol, search.location, state);
+ addReference(referenceLocation, relatedSymbol, state);
break;
case 1:
addConstructorReferences(referenceLocation, sourceFile, search, state);
@@ -70775,7 +71054,7 @@ var ts;
addRef();
}
if (!state.options.isForRename && state.markSeenReExportRHS(name)) {
- addReference(name, referenceSymbol, name, state);
+ addReference(name, referenceSymbol, state);
}
}
else {
@@ -70795,7 +71074,7 @@ var ts;
searchForImportedSymbol(imported, state);
}
function addRef() {
- addReference(referenceLocation, localSymbol, search.location, state);
+ addReference(referenceLocation, localSymbol, state);
}
}
function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
@@ -70829,11 +71108,11 @@ var ts;
var flags = _a.flags, valueDeclaration = _a.valueDeclaration;
var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
if (!(flags & 33554432) && search.includes(shorthandValueSymbol)) {
- addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state);
+ addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state);
}
}
- function addReference(referenceLocation, relatedSymbol, searchLocation, state) {
- var addRef = state.referenceAdder(relatedSymbol, searchLocation);
+ function addReference(referenceLocation, relatedSymbol, state) {
+ var addRef = state.referenceAdder(relatedSymbol);
if (state.options.implementations) {
addImplementationReferences(referenceLocation, addRef, state);
}
@@ -70843,9 +71122,9 @@ var ts;
}
function addConstructorReferences(referenceLocation, sourceFile, search, state) {
if (ts.isNewExpressionTarget(referenceLocation)) {
- addReference(referenceLocation, search.symbol, search.location, state);
+ addReference(referenceLocation, search.symbol, state);
}
- var pusher = function () { return state.referenceAdder(search.symbol, search.location); };
+ var pusher = function () { return state.referenceAdder(search.symbol); };
if (ts.isClassLike(referenceLocation.parent)) {
ts.Debug.assert(referenceLocation.kind === 79 || referenceLocation.parent.name === referenceLocation);
findOwnConstructorReferences(search.symbol, sourceFile, pusher());
@@ -70858,10 +71137,10 @@ var ts;
}
}
function addClassStaticThisReferences(referenceLocation, search, state) {
- addReference(referenceLocation, search.symbol, search.location, state);
- if (ts.isClassLike(referenceLocation.parent)) {
+ addReference(referenceLocation, search.symbol, state);
+ if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) {
ts.Debug.assert(referenceLocation.parent.name === referenceLocation);
- addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location));
+ addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol));
}
}
function addStaticThisReferences(classLike, pusher) {
@@ -70977,7 +71256,7 @@ var ts;
return result;
}
function getContainingTypeReference(node) {
- var topLevelTypeReference = undefined;
+ var topLevelTypeReference;
while (node) {
if (ts.isTypeNode(node)) {
topLevelTypeReference = node;
@@ -71081,21 +71360,16 @@ var ts;
default:
return undefined;
}
- var references = [];
var sourceFile = searchSpaceNode.getSourceFile();
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode);
- for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) {
- var position = possiblePositions_3[_i];
+ var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) {
var node = ts.getTouchingWord(sourceFile, position, false);
if (!node || node.kind !== 97) {
- continue;
+ return;
}
var container = ts.getSuperContainer(node, false);
- if (container && (32 & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) {
- references.push(FindAllReferences.nodeEntry(node));
- }
- }
- return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol, node: superKeyword }, references: references }];
+ return container && (32 & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined;
+ });
+ return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }];
}
function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false);
@@ -71125,18 +71399,11 @@ var ts;
return undefined;
}
var references = [];
- var possiblePositions;
- if (searchSpaceNode.kind === 272) {
- ts.forEach(sourceFiles, function (sourceFile) {
- cancellationToken.throwIfCancellationRequested();
- possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this");
- getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, staticFlag, references);
- });
- }
- else {
- var sourceFile = searchSpaceNode.getSourceFile();
- possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode);
- getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, references);
+ for (var _i = 0, _a = searchSpaceNode.kind === 272 ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ cancellationToken.throwIfCancellationRequested();
+ var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode);
+ getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 ? sourceFile : searchSpaceNode, positions, staticFlag, references);
}
return [{
definition: { type: "this", node: thisOrSuperKeyword },
@@ -71178,26 +71445,17 @@ var ts;
});
}
function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
- var references = [];
- for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
- var sourceFile = sourceFiles_7[_i];
+ var references = ts.flatMap(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text);
- getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references);
- }
+ return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) {
+ var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, false), ts.isStringLiteral);
+ return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, true) : undefined;
+ });
+ });
return [{
definition: { type: "string", node: node },
references: references
}];
- function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) {
- for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) {
- var position = possiblePositions_4[_i];
- var node_8 = ts.getTouchingWord(sourceFile, position, false);
- if (node_8 && node_8.kind === 9 && node_8.text === searchText) {
- references.push(FindAllReferences.nodeEntry(node_8, true));
- }
- }
- }
}
function populateSearchSymbolSet(symbol, location, checker, implementations) {
var result = [];
@@ -71338,7 +71596,9 @@ var ts;
return symbol ? [symbol] :
contextualType && contextualType.flags & 131072 ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray;
}
- function getIntersectingMeaningFromDeclarations(meaning, declarations) {
+ function getIntersectingMeaningFromDeclarations(node, symbol) {
+ var meaning = ts.getMeaningFromLocation(node);
+ var declarations = symbol.declarations;
if (declarations) {
var lastIterationMeaning = void 0;
do {
@@ -71354,6 +71614,7 @@ var ts;
}
return meaning;
}
+ Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
function isImplementation(node) {
if (!node) {
return false;
@@ -71448,9 +71709,8 @@ var ts;
return undefined;
}
if (ts.isJumpStatementTarget(node)) {
- var labelName = node.text;
- var label = ts.getTargetLabel(node.parent, labelName);
- return label ? [createDefinitionInfoFromName(label, "label", labelName, undefined)] : undefined;
+ var label = ts.getTargetLabel(node.parent, node.text);
+ return label ? [createDefinitionInfoFromName(label, "label", node.text, undefined)] : undefined;
}
var typeChecker = program.getTypeChecker();
var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
@@ -72229,7 +72489,7 @@ var ts;
case 6:
return "Package name '" + typing + "' contains non URI safe characters";
case 0:
- throw ts.Debug.fail();
+ return ts.Debug.fail();
default:
ts.Debug.assertNever(result);
}
@@ -72253,8 +72513,8 @@ var ts;
getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems);
});
};
- for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) {
- var sourceFile = sourceFiles_8[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
_loop_8(sourceFile);
}
rawItems.sort(compareNavigateToItems);
@@ -72309,37 +72569,31 @@ var ts;
return true;
}
function tryAddSingleDeclarationName(declaration, containers) {
- if (declaration) {
- var name = ts.getNameOfDeclaration(declaration);
- if (name) {
- var text = ts.getTextOfIdentifierOrLiteral(name);
- if (text !== undefined) {
- containers.unshift(text);
- }
- else if (name.kind === 146) {
- return tryAddComputedPropertyName(name.expression, containers, true);
- }
- else {
- return false;
- }
- }
+ var name = ts.getNameOfDeclaration(declaration);
+ if (name && ts.isPropertyNameLiteral(name)) {
+ containers.unshift(ts.getTextOfIdentifierOrLiteral(name));
+ return true;
+ }
+ else if (name && name.kind === 146) {
+ return tryAddComputedPropertyName(name.expression, containers, true);
+ }
+ else {
+ return false;
}
- return true;
}
function tryAddComputedPropertyName(expression, containers, includeLastPortion) {
- var text = ts.getTextOfIdentifierOrLiteral(expression);
- if (text !== undefined) {
+ if (ts.isPropertyNameLiteral(expression)) {
+ var text = ts.getTextOfIdentifierOrLiteral(expression);
if (includeLastPortion) {
containers.unshift(text);
}
return true;
}
- if (expression.kind === 183) {
- var propertyAccess = expression;
+ if (ts.isPropertyAccessExpression(expression)) {
if (includeLastPortion) {
- containers.unshift(propertyAccess.name.text);
+ containers.unshift(expression.name.text);
}
- return tryAddComputedPropertyName(propertyAccess.expression, containers, true);
+ return tryAddComputedPropertyName(expression.expression, containers, true);
}
return false;
}
@@ -72945,39 +73199,87 @@ var ts;
(function (ts) {
var OrganizeImports;
(function (OrganizeImports) {
- function organizeImports(sourceFile, formatContext, host) {
- var oldImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
- if (oldImportDecls.length === 0) {
- return [];
- }
- var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
- var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) {
- return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier);
- });
- var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
- return getExternalModuleName(importGroup[0].moduleSpecifier)
- ? coalesceImports(removeUnusedImports(importGroup))
- : importGroup;
- });
+ function organizeImports(sourceFile, formatContext, host, program) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
- if (newImportDecls.length === 0) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[0]);
- }
- else {
- changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: false,
- useNonAdjustedEndPosition: false,
- suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
- });
- }
- for (var i = 1; i < oldImportDecls.length; i++) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
+ var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
+ organizeImportsWorker(topLevelImportDecls);
+ for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
+ var ambientModule = _a[_i];
+ var ambientModuleBody = getModuleBlock(ambientModule);
+ var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
+ organizeImportsWorker(ambientModuleImportDecls);
}
return changeTracker.getChanges();
+ function organizeImportsWorker(oldImportDecls) {
+ if (ts.length(oldImportDecls) === 0) {
+ return;
+ }
+ var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
+ var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
+ var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
+ return getExternalModuleName(importGroup[0].moduleSpecifier)
+ ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
+ : importGroup;
+ });
+ if (newImportDecls.length === 0) {
+ changeTracker.deleteNode(sourceFile, oldImportDecls[0]);
+ }
+ else {
+ changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
+ useNonAdjustedStartPosition: false,
+ useNonAdjustedEndPosition: false,
+ suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
+ });
+ }
+ for (var i = 1; i < oldImportDecls.length; i++) {
+ changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
+ }
+ }
}
OrganizeImports.organizeImports = organizeImports;
- function removeUnusedImports(oldImports) {
- return oldImports;
+ function getModuleBlock(moduleDecl) {
+ var body = moduleDecl.body;
+ return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body));
+ }
+ function removeUnusedImports(oldImports, sourceFile, program) {
+ var typeChecker = program.getTypeChecker();
+ var jsxNamespace = typeChecker.getJsxNamespace();
+ var jsxContext = sourceFile.languageVariant === 1 && program.getCompilerOptions().jsx;
+ var usedImports = [];
+ for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
+ var importDecl = oldImports_1[_i];
+ var importClause = importDecl.importClause;
+ if (!importClause) {
+ usedImports.push(importDecl);
+ continue;
+ }
+ var name = importClause.name, namedBindings = importClause.namedBindings;
+ if (name && !isDeclarationUsed(name)) {
+ name = undefined;
+ }
+ if (namedBindings) {
+ if (ts.isNamespaceImport(namedBindings)) {
+ if (!isDeclarationUsed(namedBindings.name)) {
+ namedBindings = undefined;
+ }
+ }
+ else {
+ var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.propertyName || e.name); });
+ if (newElements.length < namedBindings.elements.length) {
+ namedBindings = newElements.length
+ ? ts.updateNamedImports(namedBindings, newElements)
+ : undefined;
+ }
+ }
+ }
+ if (name || namedBindings) {
+ usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
+ }
+ }
+ return usedImports;
+ function isDeclarationUsed(identifier) {
+ return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
+ }
}
function getExternalModuleName(specifier) {
return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier)
@@ -72988,20 +73290,22 @@ var ts;
if (importGroup.length === 0) {
return importGroup;
}
- var _a = getImportParts(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports;
+ var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports;
var coalescedImports = [];
if (importWithoutClause) {
coalescedImports.push(importWithoutClause);
}
if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
- var defaultImportClause = defaultImports[0].parent;
- coalescedImports.push(updateImportDeclarationAndClause(defaultImportClause, defaultImportClause.name, namespaceImports[0]));
+ var defaultImport = defaultImports[0];
+ coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings));
return coalescedImports;
}
- var sortedNamespaceImports = ts.stableSort(namespaceImports, function (n1, n2) { return compareIdentifiers(n1.name, n2.name); });
+ var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) {
+ return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name);
+ });
for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) {
var namespaceImport = sortedNamespaceImports_1[_i];
- coalescedImports.push(updateImportDeclarationAndClause(namespaceImport.parent, undefined, namespaceImport));
+ coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, undefined, namespaceImport.importClause.namedBindings));
}
if (defaultImports.length === 0 && namedImports.length === 0) {
return coalescedImports;
@@ -73009,30 +73313,30 @@ var ts;
var newDefaultImport;
var newImportSpecifiers = [];
if (defaultImports.length === 1) {
- newDefaultImport = defaultImports[0];
+ newDefaultImport = defaultImports[0].importClause.name;
}
else {
for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) {
var defaultImport = defaultImports_1[_b];
- newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport));
+ newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name));
}
}
- newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (n) { return n.elements; }));
+ newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
- var importClause = defaultImports.length > 0
- ? defaultImports[0].parent
- : namedImports[0].parent;
+ var importDecl = defaultImports.length > 0
+ ? defaultImports[0]
+ : namedImports[0];
var newNamedImports = sortedImportSpecifiers.length === 0
? undefined
: namedImports.length === 0
? ts.createNamedImports(sortedImportSpecifiers)
- : ts.updateNamedImports(namedImports[0], sortedImportSpecifiers);
- coalescedImports.push(updateImportDeclarationAndClause(importClause, newDefaultImport, newNamedImports));
+ : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers);
+ coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports));
return coalescedImports;
- function getImportParts(importGroup) {
+ function getCategorizedImports(importGroup) {
var importWithoutClause;
var defaultImports = [];
var namespaceImports = [];
@@ -73045,14 +73349,14 @@ var ts;
}
var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
if (name) {
- defaultImports.push(name);
+ defaultImports.push(importDeclaration);
}
if (namedBindings) {
if (ts.isNamespaceImport(namedBindings)) {
- namespaceImports.push(namedBindings);
+ namespaceImports.push(importDeclaration);
}
else {
- namedImports.push(namedBindings);
+ namedImports.push(importDeclaration);
}
}
}
@@ -73066,12 +73370,11 @@ var ts;
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseSensitive(s1.text, s2.text);
}
- function updateImportDeclarationAndClause(importClause, name, namedBindings) {
- var importDeclaration = importClause.parent;
- return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, name, namedBindings), importDeclaration.moduleSpecifier);
- }
}
OrganizeImports.coalesceImports = coalesceImports;
+ function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
+ return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
+ }
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
var name2 = getExternalModuleName(m2);
@@ -73122,8 +73425,8 @@ var ts;
continue;
}
if (!result[1]) {
- var span_13 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span_13, span_13, false, result[2] || "#region"));
+ var span_12 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
+ regions.push(createOutliningSpan(span_12, span_12, false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -73319,9 +73622,9 @@ var ts;
if (index > 0) {
var wordSpans = getWordSpans(candidate);
for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
- var span_14 = wordSpans_1[_i];
- if (partStartsWith(candidate, span_14, chunk.text, true)) {
- return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span_14, chunk.text, false));
+ var span_13 = wordSpans_1[_i];
+ if (partStartsWith(candidate, span_13, chunk.text, true)) {
+ return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span_13, chunk.text, false));
}
}
}
@@ -73370,7 +73673,7 @@ var ts;
}
}
var subWordTextChunks = segment.subWordTextChunks;
- var matches = undefined;
+ var matches;
for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) {
var subWordTextChunk = subWordTextChunks_1[_i];
var result = matchTextChunk(candidate, subWordTextChunk, true);
@@ -73412,8 +73715,8 @@ var ts;
var chunkCharacterSpans = chunk.characterSpans;
var currentCandidate = 0;
var currentChunkSpan = 0;
- var firstMatch = undefined;
- var contiguous = undefined;
+ var firstMatch;
+ var contiguous;
while (true) {
if (currentChunkSpan === chunkCharacterSpans.length) {
var weight = 0;
@@ -73652,11 +73955,18 @@ var ts;
function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
if (readImportFiles === void 0) { readImportFiles = true; }
if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
- var referencedFiles = [];
- var typeReferenceDirectives = [];
+ var pragmaContext = {
+ languageVersion: 1,
+ pragmas: undefined,
+ checkJsDirective: undefined,
+ referencedFiles: [],
+ typeReferenceDirectives: [],
+ amdDependencies: [],
+ hasNoDefaultLib: undefined,
+ moduleName: undefined
+ };
var importedFiles = [];
var ambientExternalModules;
- var isNoDefaultLib = false;
var braceNesting = 0;
var externalModule = false;
function nextToken() {
@@ -73669,23 +73979,6 @@ var ts;
}
return token;
}
- function processTripleSlashDirectives() {
- var commentRanges = ts.getLeadingCommentRanges(sourceText, 0);
- ts.forEach(commentRanges, function (commentRange) {
- var comment = sourceText.substring(commentRange.pos, commentRange.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange);
- if (referencePathMatchResult) {
- isNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var fileReference = referencePathMatchResult.fileReference;
- if (fileReference) {
- var collection = referencePathMatchResult.isTypeReferenceDirective
- ? typeReferenceDirectives
- : referencedFiles;
- collection.push(fileReference);
- }
- }
- });
- }
function getFileReference() {
var fileName = ts.scanner.getTokenValue();
var pos = ts.scanner.getTokenPos();
@@ -73903,7 +74196,8 @@ var ts;
if (readImportFiles) {
processImports();
}
- processTripleSlashDirectives();
+ ts.processCommentPragmas(pragmaContext, sourceText);
+ ts.processPragmasIntoFields(pragmaContext, ts.noop);
if (externalModule) {
if (ambientExternalModules) {
for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) {
@@ -73911,7 +74205,7 @@ var ts;
importedFiles.push(decl.ref);
}
}
- return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined };
+ return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined };
}
else {
var ambientModuleNames = void 0;
@@ -73929,7 +74223,7 @@ var ts;
}
}
}
- return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames };
+ return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
}
}
ts.preProcessFile = preProcessFile;
@@ -73958,20 +74252,15 @@ var ts;
function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) {
var symbol = typeChecker.getSymbolAtLocation(node);
if (symbol) {
- var declarations = symbol.getDeclarations();
+ var declarations = symbol.declarations;
if (declarations && declarations.length > 0) {
- if (ts.some(declarations, isDefinedInLibraryFile)) {
+ if (declarations.some(isDefinedInLibraryFile)) {
return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
}
- if (node.kind === 71 &&
- node.originalKeywordKind === 79 &&
- symbol.parent.flags & 1536) {
+ if (ts.isIdentifier(node) && node.originalKeywordKind === 79 && symbol.parent.flags & 1536) {
return undefined;
}
var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
- if (!kind) {
- return undefined;
- }
var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146)
? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
: undefined;
@@ -73980,12 +74269,11 @@ var ts;
return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
}
}
- else if (node.kind === 9) {
+ else if (ts.isStringLiteral(node)) {
if (isDefinedInLibraryFile(node)) {
return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
}
- var displayName = ts.stripQuotes(node.text);
- return getRenameInfoSuccess(displayName, displayName, "var", "", node, sourceFile);
+ return getRenameInfoSuccess(node.text, node.text, "var", "", node, sourceFile);
}
}
function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
@@ -74342,6 +74630,62 @@ var ts;
})(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {}));
})(ts || (ts = {}));
var ts;
+(function (ts) {
+ function computeSuggestionDiagnostics(sourceFile, program) {
+ program.getSemanticDiagnostics(sourceFile);
+ var checker = program.getDiagnosticsProducingTypeChecker();
+ var diags = [];
+ if (sourceFile.commonJsModuleIndicator) {
+ diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
+ }
+ var isJsFile = ts.isSourceFileJavaScript(sourceFile);
+ function check(node) {
+ switch (node.kind) {
+ case 232:
+ case 190:
+ if (isJsFile) {
+ var symbol = node.symbol;
+ if (symbol.members && (symbol.members.size > 0)) {
+ diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
+ }
+ }
+ break;
+ }
+ if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) {
+ diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
+ }
+ node.forEachChild(check);
+ }
+ check(sourceFile);
+ if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
+ for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
+ var importNode = _a[_i];
+ var name = importNameForConvertToDefaultImport(importNode.parent);
+ if (!name)
+ continue;
+ var module_2 = ts.getResolvedModule(sourceFile, importNode.text);
+ var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
+ if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
+ diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
+ }
+ }
+ }
+ return diags.concat(checker.getSuggestionDiagnostics(sourceFile));
+ }
+ ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
+ function importNameForConvertToDefaultImport(node) {
+ if (ts.isExternalModuleReference(node)) {
+ return node.parent.name;
+ }
+ if (ts.isImportDeclaration(node)) {
+ var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier;
+ return importClause && !importClause.name && importClause.namedBindings.kind === 244 && ts.isStringLiteral(moduleSpecifier)
+ ? importClause.namedBindings.name
+ : undefined;
+ }
+ }
+})(ts || (ts = {}));
+var ts;
(function (ts) {
var SymbolDisplay;
(function (SymbolDisplay) {
@@ -77167,25 +77511,13 @@ var ts;
function isControlFlowEndingStatement(kind, parent) {
switch (kind) {
case 223:
- case 227:
- switch (parent.kind) {
- case 211:
- var grandParent = parent.parent;
- switch (grandParent && grandParent.kind) {
- case 232:
- case 190:
- return false;
- default:
- return true;
- }
- case 264:
- case 265:
- case 272:
- case 238:
- return true;
- default:
- throw ts.Debug.fail();
+ case 227: {
+ if (parent.kind !== 211) {
+ return true;
}
+ var grandParent = parent.parent;
+ return !(grandParent && grandParent.kind === 190 || grandParent.kind === 232);
+ }
case 221:
case 222:
return true;
@@ -77300,10 +77632,9 @@ var ts;
return s;
}
var ChangeTracker = (function () {
- function ChangeTracker(newLineCharacter, formatContext, validator) {
+ function ChangeTracker(newLineCharacter, formatContext) {
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
- this.validator = validator;
this.changes = [];
this.deletedNodesInLists = [];
this.nodesInsertedAtClassStarts = ts.createMap();
@@ -77438,7 +77769,7 @@ var ts;
else if (ts.isVariableDeclaration(before)) {
return { suffix: ", " };
}
- throw ts.Debug.failBadSyntaxKind(before);
+ return ts.Debug.failBadSyntaxKind(before);
};
ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
var firstStatement = ts.firstOrUndefined(ctr.body.statements);
@@ -77513,7 +77844,7 @@ var ts;
else if (ts.isVariableDeclaration(node)) {
return { prefix: ", " };
}
- throw ts.Debug.failBadSyntaxKind(node);
+ return ts.Debug.failBadSyntaxKind(node);
};
ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) {
var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile);
@@ -77612,88 +77943,72 @@ var ts;
_this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true });
});
};
- ChangeTracker.prototype.getChanges = function () {
- var _this = this;
+ ChangeTracker.prototype.getChanges = function (validate) {
this.finishInsertNodeAtClassStart();
- return ts.group(this.changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
- var sourceFile = changesInFile[0].sourceFile;
- var textChanges = ChangeTracker.normalize(changesInFile).map(function (c) {
- return ts.createTextChange(ts.createTextSpanFromRange(c.range), _this.computeNewText(c, sourceFile));
- });
- return { fileName: sourceFile.fileName, textChanges: textChanges };
- });
- };
- ChangeTracker.prototype.computeNewText = function (change, sourceFile) {
- var _this = this;
- if (change.kind === ChangeKind.Remove) {
- return "";
- }
- var options = change.options || {};
- var text;
- var pos = change.range.pos;
- var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos;
- if (change.kind === ChangeKind.ReplaceWithMultipleNodes) {
- var lastIndex_1 = change.nodes.length - 1;
- var parts = change.nodes.map(function (n, index) {
- var formatted = _this.getFormattedTextOfNode(n, sourceFile, pos, options);
- return index === lastIndex_1 || ts.endsWith(formatted, _this.newLineCharacter)
- ? formatted
- : (formatted + _this.newLineCharacter);
- });
- text = parts.join("");
- }
- else {
- ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode");
- text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options);
- }
- text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, "");
- return (options.prefix || "") + text + (options.suffix || "");
- };
- ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) {
- var nonformattedText = getNonformattedText(node, sourceFile, this.newLineCharacter);
- if (this.validator) {
- this.validator(nonformattedText);
- }
- var formatOptions = this.formatContext.options;
- var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos;
- var initialIndentation = options.indentation !== undefined
- ? options.indentation
- : (options.useIndentationFromFile !== false)
- ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter))
- : 0;
- var delta = options.delta !== undefined
- ? options.delta
- : ts.formatting.SmartIndenter.shouldIndentChildNode(node)
- ? (formatOptions.indentSize || 0)
- : 0;
- return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.formatContext);
- };
- ChangeTracker.normalize = function (changes) {
- var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; });
- for (var i = 0; i < normalized.length - 2; i++) {
- ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos);
- }
- return normalized;
+ return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
};
return ChangeTracker;
}());
textChanges_1.ChangeTracker = ChangeTracker;
- function getNonformattedText(node, sourceFile, newLine) {
- var writer = new Writer(newLine);
- var printer = ts.createPrinter({ newLine: newLine === "\n" ? 1 : 0 }, writer);
- printer.writeNode(4, node, sourceFile, writer);
- return { text: writer.getText(), node: assignPositionsToNode(node) };
- }
- function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, formatContext) {
- var lineMap = ts.computeLineStarts(nonFormattedText.text);
- var file = {
- text: nonFormattedText.text,
- lineMap: lineMap,
- getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); }
- };
- var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext);
- return applyChanges(nonFormattedText.text, changes);
- }
+ var changesToText;
+ (function (changesToText) {
+ function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
+ return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
+ var sourceFile = changesInFile[0].sourceFile;
+ var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
+ var _loop_10 = 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);
+ });
+ };
+ for (var i = 0; i < normalized.length - 2; i++) {
+ _loop_10(i);
+ }
+ var textChanges = normalized.map(function (c) {
+ return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
+ });
+ return { fileName: sourceFile.fileName, textChanges: textChanges };
+ });
+ }
+ changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
+ if (change.kind === ChangeKind.Remove) {
+ return "";
+ }
+ var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos;
+ var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); };
+ var text = change.kind === ChangeKind.ReplaceWithMultipleNodes
+ ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter)
+ : format(change.node);
+ var noIndent = (options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, "");
+ return (options.prefix || "") + noIndent + (options.suffix || "");
+ }
+ function getFormattedTextOfNode(nodeIn, sourceFile, pos, options, newLineCharacter, formatContext, validate) {
+ var _a = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _a.node, text = _a.text;
+ if (validate)
+ validate(node, text);
+ var formatOptions = formatContext.options;
+ var initialIndentation = options.indentation !== undefined
+ ? options.indentation
+ : (options.useIndentationFromFile !== false)
+ ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, options.prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos)
+ : 0;
+ var delta = options.delta !== undefined
+ ? options.delta
+ : ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn)
+ ? (formatOptions.indentSize || 0)
+ : 0;
+ var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } };
+ var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext);
+ return applyChanges(text, changes);
+ }
+ function getNonformattedText(node, sourceFile, newLineCharacter) {
+ var writer = new Writer(newLineCharacter);
+ var newLine = newLineCharacter === "\n" ? 1 : 0;
+ ts.createPrinter({ newLine: newLine }, writer).writeNode(4, node, sourceFile, writer);
+ return { text: writer.getText(), node: assignPositionsToNode(node) };
+ }
+ })(changesToText || (changesToText = {}));
function applyChanges(text, changes) {
for (var i = changes.length - 1; i >= 0; i--) {
var change = changes[i];
@@ -77964,7 +78279,7 @@ var ts;
codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges;
function eachDiagnostic(_a, errorCodes, cb) {
var program = _a.program, sourceFile = _a.sourceFile;
- for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) {
+ for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) {
var diag = _b[_i];
if (ts.contains(errorCodes, diag.code)) {
cb(diag);
@@ -78024,6 +78339,742 @@ var ts;
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "annotateWithTypeFromJSDoc";
+ var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var decl = getDeclaration(context.sourceFile, context.span.start);
+ if (!decl)
+ return;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Annotate_with_type_from_JSDoc);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); });
+ return [{ description: description, changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var decl = getDeclaration(diag.file, diag.start);
+ if (decl)
+ doChange(changes, diag.file, decl);
+ }); },
+ });
+ function getDeclaration(file, pos) {
+ var name = ts.getTokenAtPosition(file, pos, false);
+ return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
+ }
+ function parameterShouldGetTypeFromJSDoc(node) {
+ return isDeclarationWithType(node) && hasUsableJSDoc(node);
+ }
+ codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc;
+ function hasUsableJSDoc(decl) {
+ return ts.isFunctionLikeDeclaration(decl)
+ ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl))
+ : !decl.type && !!ts.getJSDocType(decl);
+ }
+ function doChange(changes, sourceFile, decl) {
+ if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
+ ts.findAncestor(decl, ts.isFunctionLike);
+ var fn = ts.findAncestor(decl, ts.isFunctionLikeDeclaration);
+ var functionWithType = addTypesToFunctionLike(fn);
+ ts.suppressLeadingAndTrailingTrivia(functionWithType);
+ changes.replaceNode(sourceFile, fn, functionWithType, ts.textChanges.useNonAdjustedPositions);
+ return;
+ }
+ else {
+ var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl));
+ ts.Debug.assert(!decl.type);
+ var declarationWithType = addType(decl, transformJSDocType(jsdocType));
+ ts.suppressLeadingAndTrailingTrivia(declarationWithType);
+ changes.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions);
+ }
+ }
+ function isDeclarationWithType(node) {
+ return ts.isFunctionLikeDeclaration(node) ||
+ node.kind === 230 ||
+ node.kind === 150 ||
+ node.kind === 151;
+ }
+ function addTypesToFunctionLike(decl) {
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, true);
+ var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, true)), p.initializer); });
+ var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, true));
+ switch (decl.kind) {
+ case 232:
+ return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
+ case 154:
+ return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body);
+ case 190:
+ return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
+ case 191:
+ return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body);
+ case 153:
+ return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body);
+ case 155:
+ return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body);
+ case 156:
+ return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body);
+ default:
+ return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind);
+ }
+ }
+ function addType(decl, jsdocType) {
+ switch (decl.kind) {
+ case 230:
+ return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer);
+ case 150:
+ return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
+ case 151:
+ return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
+ default:
+ return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind);
+ }
+ }
+ function transformJSDocType(node) {
+ if (node === undefined) {
+ return undefined;
+ }
+ switch (node.kind) {
+ case 275:
+ case 276:
+ return ts.createTypeReferenceNode("any", ts.emptyArray);
+ case 279:
+ return transformJSDocOptionalType(node);
+ case 278:
+ return transformJSDocType(node.type);
+ case 277:
+ return transformJSDocNullableType(node);
+ case 281:
+ return transformJSDocVariadicType(node);
+ case 280:
+ return transformJSDocFunctionType(node);
+ case 148:
+ return transformJSDocParameter(node);
+ case 161:
+ return transformJSDocTypeReference(node);
+ default:
+ var visited = ts.visitEachChild(node, transformJSDocType, undefined);
+ ts.setEmitFlags(visited, 1);
+ return visited;
+ }
+ }
+ function transformJSDocOptionalType(node) {
+ return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
+ }
+ function transformJSDocNullableType(node) {
+ return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
+ }
+ function transformJSDocVariadicType(node) {
+ return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
+ }
+ function transformJSDocFunctionType(node) {
+ var parameters = node.parameters && node.parameters.map(transformJSDocType);
+ return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type);
+ }
+ function transformJSDocParameter(node) {
+ var index = node.parent.parameters.indexOf(node);
+ var isRest = node.type.kind === 281 && index === node.parent.parameters.length - 1;
+ var name = node.name || (isRest ? "rest" : "arg" + index);
+ var dotdotdot = isRest ? ts.createToken(24) : node.dotDotDotToken;
+ return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
+ }
+ function transformJSDocTypeReference(node) {
+ var name = node.typeName;
+ var args = node.typeArguments;
+ if (ts.isIdentifier(node.typeName)) {
+ if (ts.isJSDocIndexSignature(node)) {
+ return transformJSDocIndexSignature(node);
+ }
+ var text = node.typeName.text;
+ switch (node.typeName.text) {
+ case "String":
+ case "Boolean":
+ case "Object":
+ case "Number":
+ text = text.toLowerCase();
+ break;
+ case "array":
+ case "date":
+ case "promise":
+ text = text[0].toUpperCase() + text.slice(1);
+ break;
+ }
+ name = ts.createIdentifier(text);
+ if ((text === "Array" || text === "Promise") && !node.typeArguments) {
+ args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
+ }
+ else {
+ args = ts.visitNodes(node.typeArguments, transformJSDocType);
+ }
+ }
+ return ts.createTypeReferenceNode(name, args);
+ }
+ function transformJSDocIndexSignature(node) {
+ var index = ts.createParameter(undefined, undefined, undefined, node.typeArguments[0].kind === 134 ? "n" : "s", undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 ? "number" : "string", []), undefined);
+ var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(undefined, undefined, [index], node.typeArguments[1])]);
+ ts.setEmitFlags(indexSignature, 1);
+ return indexSignature;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "convertFunctionToEs6Class";
+ var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
+ return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_function_to_an_ES2015_class), changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
+ });
+ function doChange(changes, sourceFile, position, checker) {
+ var deletedNodes = [];
+ var deletes = [];
+ var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, false));
+ if (!ctorSymbol || !(ctorSymbol.flags & (16 | 3))) {
+ return undefined;
+ }
+ var ctorDeclaration = ctorSymbol.valueDeclaration;
+ var precedingNode;
+ var newClassDeclaration;
+ switch (ctorDeclaration.kind) {
+ case 232:
+ precedingNode = ctorDeclaration;
+ deleteNode(ctorDeclaration);
+ newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
+ break;
+ case 230:
+ precedingNode = ctorDeclaration.parent.parent;
+ if (ctorDeclaration.parent.declarations.length === 1) {
+ deleteNode(precedingNode);
+ }
+ else {
+ deleteNode(ctorDeclaration, true);
+ }
+ newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
+ break;
+ }
+ if (!newClassDeclaration) {
+ return undefined;
+ }
+ changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
+ for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) {
+ var deleteCallback = deletes_1[_i];
+ deleteCallback();
+ }
+ function deleteNode(node, inList) {
+ if (inList === void 0) { inList = false; }
+ if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) {
+ return;
+ }
+ deletedNodes.push(node);
+ if (inList) {
+ deletes.push(function () { return changes.deleteNodeInList(sourceFile, node); });
+ }
+ else {
+ deletes.push(function () { return changes.deleteNode(sourceFile, node); });
+ }
+ }
+ function createClassElementsFromSymbol(symbol) {
+ var memberElements = [];
+ if (symbol.members) {
+ symbol.members.forEach(function (member) {
+ var memberElement = createClassElement(member, undefined);
+ if (memberElement) {
+ memberElements.push(memberElement);
+ }
+ });
+ }
+ if (symbol.exports) {
+ symbol.exports.forEach(function (member) {
+ var memberElement = createClassElement(member, [ts.createToken(115)]);
+ if (memberElement) {
+ memberElements.push(memberElement);
+ }
+ });
+ }
+ return memberElements;
+ function shouldConvertDeclaration(_target, source) {
+ return ts.isFunctionLike(source);
+ }
+ function createClassElement(symbol, modifiers) {
+ if (!(symbol.flags & 4)) {
+ return;
+ }
+ var memberDeclaration = symbol.valueDeclaration;
+ var assignmentBinaryExpression = memberDeclaration.parent;
+ if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
+ return;
+ }
+ var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 214
+ ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
+ deleteNode(nodeToDelete);
+ if (!assignmentBinaryExpression.right) {
+ return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined);
+ }
+ switch (assignmentBinaryExpression.right.kind) {
+ case 190: {
+ var functionExpression = assignmentBinaryExpression.right;
+ var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120));
+ var method = ts.createMethod(undefined, fullModifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body);
+ copyComments(assignmentBinaryExpression, method, sourceFile);
+ return method;
+ }
+ case 191: {
+ var arrowFunction = assignmentBinaryExpression.right;
+ var arrowFunctionBody = arrowFunction.body;
+ var bodyBlock = void 0;
+ if (arrowFunctionBody.kind === 211) {
+ bodyBlock = arrowFunctionBody;
+ }
+ else {
+ bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
+ }
+ var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120));
+ var method = ts.createMethod(undefined, fullModifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock);
+ copyComments(assignmentBinaryExpression, method, sourceFile);
+ return method;
+ }
+ default: {
+ if (ts.isSourceFileJavaScript(sourceFile)) {
+ return;
+ }
+ var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right);
+ copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ return prop;
+ }
+ }
+ }
+ }
+ function createClassFromVariableDeclaration(node) {
+ var initializer = node.initializer;
+ if (!initializer || initializer.kind !== 190) {
+ return undefined;
+ }
+ if (node.name.kind !== 71) {
+ return undefined;
+ }
+ var memberElements = createClassElementsFromSymbol(initializer.symbol);
+ if (initializer.body) {
+ memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body));
+ }
+ var modifiers = getModifierKindFromSource(precedingNode, 84);
+ var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements);
+ return cls;
+ }
+ function createClassFromFunctionDeclaration(node) {
+ var memberElements = createClassElementsFromSymbol(ctorSymbol);
+ if (node.body) {
+ memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body));
+ }
+ var modifiers = getModifierKindFromSource(node, 84);
+ var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements);
+ return cls;
+ }
+ }
+ function copyComments(sourceNode, targetNode, sourceFile) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ if (kind === 3) {
+ pos += 2;
+ end -= 2;
+ }
+ else {
+ pos += 2;
+ }
+ ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl);
+ });
+ }
+ function getModifierKindFromSource(source, kind) {
+ return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code],
+ getCodeActions: function (context) {
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module);
+ var sourceFile = context.sourceFile, program = context.program;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
+ var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target);
+ if (moduleExportsChangedToDefault) {
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var importingFile = _a[_i];
+ fixImportOfModuleExports(importingFile, sourceFile, changes);
+ }
+ }
+ });
+ return [{ description: description, changes: changes, fixId: undefined }];
+ },
+ });
+ function fixImportOfModuleExports(importingFile, exportingFile, changes) {
+ for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
+ var moduleSpecifier = _a[_i];
+ var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
+ if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
+ continue;
+ }
+ var parent = moduleSpecifier.parent;
+ switch (parent.kind) {
+ case 252: {
+ var importEq = parent.parent;
+ changes.replaceNode(importingFile, importEq, makeImport(importEq.name, undefined, moduleSpecifier.text));
+ break;
+ }
+ case 185: {
+ var call = parent;
+ if (ts.isRequireCall(call, false)) {
+ changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default"));
+ }
+ break;
+ }
+ }
+ }
+ }
+ function convertFileToEs6Module(sourceFile, checker, changes, target) {
+ var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
+ var exports = collectExportRenames(sourceFile, checker, identifiers);
+ convertExportsAccesses(sourceFile, exports, changes);
+ var moduleExportsChangedToDefault = false;
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports);
+ moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
+ }
+ return moduleExportsChangedToDefault;
+ }
+ function collectExportRenames(sourceFile, checker, identifiers) {
+ var res = ts.createMap();
+ forEachExportReference(sourceFile, function (node) {
+ var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
+ if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
+ || checker.resolveName(node.name.text, node, 107455, true))) {
+ res.set(text, makeUniqueName("_" + text, identifiers));
+ }
+ });
+ return res;
+ }
+ function convertExportsAccesses(sourceFile, exports, changes) {
+ forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
+ if (isAssignmentLhs) {
+ return;
+ }
+ var text = node.name.text;
+ changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
+ });
+ }
+ function forEachExportReference(sourceFile, cb) {
+ sourceFile.forEachChild(function recur(node) {
+ if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
+ var parent = node.parent;
+ cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58);
+ }
+ node.forEachChild(recur);
+ });
+ }
+ function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) {
+ switch (statement.kind) {
+ case 212:
+ convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target);
+ return false;
+ case 214: {
+ var expression = statement.expression;
+ switch (expression.kind) {
+ case 185: {
+ if (ts.isRequireCall(expression, true)) {
+ changes.replaceNode(sourceFile, statement, makeImport(undefined, undefined, expression.arguments[0].text));
+ }
+ return false;
+ }
+ case 198: {
+ var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
+ return operatorToken.kind === 58 && convertAssignment(sourceFile, checker, statement, left, right, changes, exports);
+ }
+ }
+ }
+ default:
+ return false;
+ }
+ }
+ function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) {
+ var declarationList = statement.declarationList;
+ var foundImport = false;
+ var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
+ var name = decl.name, initializer = decl.initializer;
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
+ foundImport = true;
+ return [];
+ }
+ if (ts.isRequireCall(initializer, true)) {
+ foundImport = true;
+ return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target);
+ }
+ else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, true)) {
+ foundImport = true;
+ return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers);
+ }
+ else {
+ return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
+ }
+ });
+ if (foundImport) {
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ }
+ }
+ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) {
+ switch (name.kind) {
+ case 178:
+ case 179: {
+ var tmp = makeUniqueName(propertyName, identifiers);
+ return [
+ makeSingleImport(tmp, propertyName, moduleSpecifier),
+ makeConst(undefined, name, ts.createIdentifier(tmp)),
+ ];
+ }
+ case 71:
+ return [makeSingleImport(name.text, propertyName, moduleSpecifier)];
+ default:
+ ts.Debug.assertNever(name);
+ }
+ }
+ function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) {
+ if (!ts.isPropertyAccessExpression(left)) {
+ return false;
+ }
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
+ changes.deleteNode(sourceFile, statement);
+ }
+ else {
+ var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
+ var changedToDefaultExport = false;
+ if (!newNodes) {
+ (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ }
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ return changedToDefaultExport;
+ }
+ }
+ else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
+ convertNamedExport(sourceFile, statement, left.name, right, changes, exports);
+ }
+ return false;
+ var _a;
+ }
+ function tryChangeModuleExportsObject(object) {
+ return ts.mapAllOrFail(object.properties, function (prop) {
+ switch (prop.kind) {
+ case 155:
+ case 156:
+ case 269:
+ case 270:
+ return undefined;
+ case 268:
+ return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer);
+ case 153:
+ return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84)], prop);
+ default:
+ ts.Debug.assertNever(prop);
+ }
+ });
+ }
+ function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) {
+ var text = propertyName.text;
+ var rename = exports.get(text);
+ if (rename !== undefined) {
+ var newNodes = [
+ makeConst(undefined, rename, right),
+ makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
+ ];
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ }
+ else {
+ changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true });
+ }
+ }
+ function convertModuleExportsToExportDefault(exported, checker) {
+ var modifiers = [ts.createToken(84), ts.createToken(79)];
+ switch (exported.kind) {
+ case 190:
+ case 191: {
+ var fn = exported;
+ return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
+ }
+ case 203: {
+ var cls = exported;
+ return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
+ }
+ case 185:
+ if (ts.isRequireCall(exported, true)) {
+ return convertReExportAll(exported.arguments[0], checker);
+ }
+ default:
+ return [[ts.createExportAssignment(undefined, undefined, false, exported)], true];
+ }
+ }
+ function convertReExportAll(reExported, checker) {
+ var moduleSpecifier = reExported.text;
+ var moduleSymbol = checker.getSymbolAtLocation(reExported);
+ var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
+ return exports.has("export=")
+ ? [[reExportDefault(moduleSpecifier)], true]
+ : !exports.has("default")
+ ? [[reExportStar(moduleSpecifier)], false]
+ : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
+ }
+ function reExportStar(moduleSpecifier) {
+ return makeExportDeclaration(undefined, moduleSpecifier);
+ }
+ function reExportDefault(moduleSpecifier) {
+ return makeExportDeclaration([ts.createExportSpecifier(undefined, "default")], moduleSpecifier);
+ }
+ function convertExportsDotXEquals(name, exported) {
+ var modifiers = [ts.createToken(84)];
+ switch (exported.kind) {
+ case 190: {
+ var expressionName = exported.name;
+ if (expressionName && expressionName.text !== name) {
+ return exportConst();
+ }
+ }
+ case 191:
+ return functionExpressionToDeclaration(name, modifiers, exported);
+ case 203:
+ return classExpressionToDeclaration(name, modifiers, exported);
+ default:
+ return exportConst();
+ }
+ function exportConst() {
+ return makeConst(modifiers, ts.createIdentifier(name), exported);
+ }
+ }
+ function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) {
+ switch (name.kind) {
+ case 178: {
+ var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) {
+ return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name)
+ ? undefined
+ : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
+ });
+ if (importSpecifiers) {
+ return [makeImport(undefined, importSpecifiers, moduleSpecifier)];
+ }
+ }
+ case 179: {
+ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers);
+ return [
+ makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier),
+ makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
+ ];
+ }
+ case 71:
+ return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers);
+ default:
+ ts.Debug.assertNever(name);
+ }
+ }
+ function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) {
+ var nameSymbol = checker.getSymbolAtLocation(name);
+ var namedBindingsNames = ts.createMap();
+ var needDefaultImport = false;
+ for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
+ var use = _a[_i];
+ if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
+ continue;
+ }
+ var parent = use.parent;
+ if (ts.isPropertyAccessExpression(parent)) {
+ var expression = parent.expression, propertyName = parent.name.text;
+ ts.Debug.assert(expression === use);
+ var idName = namedBindingsNames.get(propertyName);
+ if (idName === undefined) {
+ idName = makeUniqueName(propertyName, identifiers);
+ namedBindingsNames.set(propertyName, idName);
+ }
+ changes.replaceNode(file, parent, ts.createIdentifier(idName));
+ }
+ else {
+ needDefaultImport = true;
+ }
+ }
+ var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
+ var propertyName = _a[0], idName = _a[1];
+ return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
+ }));
+ if (!namedBindings) {
+ needDefaultImport = true;
+ }
+ return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ }
+ function makeUniqueName(name, identifiers) {
+ while (identifiers.original.has(name) || identifiers.additional.has(name)) {
+ name = "_" + name;
+ }
+ identifiers.additional.set(name, true);
+ return name;
+ }
+ function collectFreeIdentifiers(file) {
+ var map = ts.createMultiMap();
+ file.forEachChild(function recur(node) {
+ if (ts.isIdentifier(node) && isFreeIdentifier(node)) {
+ map.add(node.text, node);
+ }
+ node.forEachChild(recur);
+ });
+ return map;
+ }
+ function isFreeIdentifier(node) {
+ var parent = node.parent;
+ switch (parent.kind) {
+ case 183:
+ return parent.name !== node;
+ case 180:
+ return parent.propertyName !== node;
+ default:
+ return true;
+ }
+ }
+ function functionExpressionToDeclaration(name, additionalModifiers, fn) {
+ return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
+ }
+ function classExpressionToDeclaration(name, additionalModifiers, cls) {
+ return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
+ }
+ function makeSingleImport(localName, propertyName, moduleSpecifier) {
+ return propertyName === "default"
+ ? makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier)
+ : makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ }
+ function makeImport(name, namedImports, moduleSpecifier) {
+ return makeImportDeclaration(name, namedImports, ts.createLiteral(moduleSpecifier));
+ }
+ function makeImportDeclaration(name, namedImports, moduleSpecifier) {
+ var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
+ return ts.createImportDeclaration(undefined, undefined, importClause, moduleSpecifier);
+ }
+ codefix.makeImportDeclaration = makeImportDeclaration;
+ function makeImportSpecifier(propertyName, name) {
+ return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
+ }
+ function makeConst(modifiers, name, init) {
+ return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, undefined, init)], 2));
+ }
+ function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
+ return ts.createExportDeclaration(undefined, undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -78095,9 +79146,7 @@ var ts;
},
});
function getClass(sourceFile, pos) {
- var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, false));
- ts.Debug.assert(!!classDeclaration);
- return classDeclaration;
+ return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, false)));
}
function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) {
var implementedType = checker.getTypeAtLocation(implementedTypeNode);
@@ -78377,7 +79426,6 @@ var ts;
commands: [getCommand(fileName, packageName)],
};
}
- codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes;
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
var ts;
@@ -78399,15 +79447,19 @@ var ts;
return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }];
},
fixIds: [fixId],
- getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
- addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes);
- }); },
+ getAllCodeActions: function (context) {
+ var seenClassDeclarations = ts.createMap();
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var classDeclaration = getClass(diag.file, diag.start);
+ if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
+ addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes);
+ }
+ });
+ },
});
function getClass(sourceFile, pos) {
var token = ts.getTokenAtPosition(sourceFile, pos, false);
- var classDeclaration = token.parent;
- ts.Debug.assert(ts.isClassLike(classDeclaration));
- return classDeclaration;
+ return ts.cast(token.parent, ts.isClassLike);
}
function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) {
var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration);
@@ -79411,7 +80463,7 @@ var ts;
var parent = token.parent;
var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent);
if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258) {
- umdSymbol = checker.resolveName(checker.getJsxNamespace(), isNodeOpeningLikeElement ? parent.tagName : parent, 107455, false);
+ umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 107455, false);
}
}
if (ts.isUMDExportSymbol(umdSymbol)) {
@@ -79438,7 +80490,7 @@ var ts;
case ts.ModuleKind.None:
return 2;
default:
- throw ts.Debug.assertNever(moduleKind);
+ return ts.Debug.assertNever(moduleKind);
}
}
function getActionsForNonUMDImport(context) {
@@ -79828,7 +80880,7 @@ var ts;
case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, program, cancellationToken) : undefined;
default:
- throw ts.Debug.fail(String(errorCode));
+ return ts.Debug.fail(String(errorCode));
}
}
function isAllowedTokenKind(kind) {
@@ -79996,13 +81048,13 @@ var ts;
var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
return callContexts && declaration.parameters.map(function (parameter, parameterIndex) {
var types = [];
- var isRestParameter = ts.isRestParameter(parameter);
+ var isRest = ts.isRestParameter(parameter);
for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) {
var callContext = callContexts_1[_i];
if (callContext.argumentTypes.length <= parameterIndex) {
continue;
}
- if (isRestParameter) {
+ if (isRest) {
for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) {
types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i]));
}
@@ -80015,7 +81067,7 @@ var ts;
return undefined;
}
var type = checker.getWidenedType(checker.getUnionType(types, 2));
- return isRestParameter ? checker.createArrayType(type) : type;
+ return isRest ? checker.createArrayType(type) : type;
});
}
InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences;
@@ -80319,7 +81371,7 @@ var ts;
var namespace = ts.getNamespaceDeclarationNode(node);
var opts = context.program.getCompilerOptions();
var variations = [];
- variations.push(createAction(context, sourceFile, node, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(namespace.name, undefined), node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(undefined, undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier))));
}
@@ -80366,871 +81418,162 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var refactor;
- (function (refactor) {
- var annotateWithTypeFromJSDoc;
- (function (annotateWithTypeFromJSDoc) {
- var refactorName = "Annotate with type from JSDoc";
- var actionName = "annotate";
- var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (ts.isInJavaScriptFile(context.file)) {
- return undefined;
- }
- var node = ts.getTokenAtPosition(context.file, context.startPosition, false);
- if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) {
- return [{
- name: refactorName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName
- }
- ]
- }];
- }
- }
- function hasUsableJSDoc(decl) {
- if (!decl) {
- return false;
- }
- if (ts.isFunctionLikeDeclaration(decl)) {
- return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl));
- }
- return !decl.type && !!ts.getJSDocType(decl);
- }
- function getEditsForAction(context, action) {
- if (actionName !== action) {
- return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action);
- }
- var node = ts.getTokenAtPosition(context.file, context.startPosition, false);
- var decl = ts.findAncestor(node, isDeclarationWithType);
- if (!decl || decl.type) {
- return undefined;
- }
- var jsdocType = ts.getJSDocType(decl);
- var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }));
- if (isFunctionWithJSDoc || jsdocType && decl.kind === 148) {
- return getEditsForFunctionAnnotation(context);
- }
- else if (jsdocType) {
- return getEditsForAnnotation(context);
- }
- else {
- ts.Debug.assert(!!refactor, "No applicable refactor found.");
- }
- }
- function getEditsForAnnotation(context) {
- var sourceFile = context.file;
- var token = ts.getTokenAtPosition(sourceFile, context.startPosition, false);
- var decl = ts.findAncestor(token, isDeclarationWithType);
- var jsdocType = ts.getJSDocType(decl);
- if (!decl || !jsdocType || decl.type) {
- return ts.Debug.fail("!decl || !jsdocType || decl.type: !" + decl + " || !" + jsdocType + " || " + decl.type);
- }
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var declarationWithType = addType(decl, transformJSDocType(jsdocType));
- ts.suppressLeadingAndTrailingTrivia(declarationWithType);
- changeTracker.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions);
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined
- };
- }
- function getEditsForFunctionAnnotation(context) {
- var sourceFile = context.file;
- var token = ts.getTokenAtPosition(sourceFile, context.startPosition, false);
- var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration);
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var functionWithType = addTypesToFunctionLike(decl);
- ts.suppressLeadingAndTrailingTrivia(functionWithType);
- changeTracker.replaceNode(sourceFile, decl, functionWithType, ts.textChanges.useNonAdjustedPositions);
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined
- };
- }
- function isDeclarationWithType(node) {
- return ts.isFunctionLikeDeclaration(node) ||
- node.kind === 230 ||
- node.kind === 148 ||
- node.kind === 150 ||
- node.kind === 151;
- }
- function addTypesToFunctionLike(decl) {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, true);
- var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, true)), p.initializer); });
- var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, true));
- switch (decl.kind) {
- case 232:
- return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
- case 154:
- return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body);
- case 190:
- return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
- case 191:
- return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body);
- case 153:
- return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body);
- case 155:
- return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body);
- case 156:
- return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body);
- default:
- return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind);
- }
- }
- function addType(decl, jsdocType) {
- switch (decl.kind) {
- case 230:
- return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer);
- case 150:
- return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
- case 151:
- return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
- default:
- return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind);
- }
- }
- function transformJSDocType(node) {
- if (node === undefined) {
- return undefined;
- }
- switch (node.kind) {
- case 275:
- case 276:
- return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 279:
- return transformJSDocOptionalType(node);
- case 278:
- return transformJSDocType(node.type);
- case 277:
- return transformJSDocNullableType(node);
- case 281:
- return transformJSDocVariadicType(node);
- case 280:
- return transformJSDocFunctionType(node);
- case 148:
- return transformJSDocParameter(node);
- case 161:
- return transformJSDocTypeReference(node);
- default:
- var visited = ts.visitEachChild(node, transformJSDocType, undefined);
- ts.setEmitFlags(visited, 1);
- return visited;
- }
- }
- function transformJSDocOptionalType(node) {
- return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
- }
- function transformJSDocNullableType(node) {
- return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
- }
- function transformJSDocVariadicType(node) {
- return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
- }
- function transformJSDocFunctionType(node) {
- var parameters = node.parameters && node.parameters.map(transformJSDocType);
- return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type);
- }
- function transformJSDocParameter(node) {
- var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 281 && index === node.parent.parameters.length - 1;
- var name = node.name || (isRest ? "rest" : "arg" + index);
- var dotdotdot = isRest ? ts.createToken(24) : node.dotDotDotToken;
- return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
- }
- function transformJSDocTypeReference(node) {
- var name = node.typeName;
- var args = node.typeArguments;
- if (ts.isIdentifier(node.typeName)) {
- if (ts.isJSDocIndexSignature(node)) {
- return transformJSDocIndexSignature(node);
- }
- var text = node.typeName.text;
- switch (node.typeName.text) {
- case "String":
- case "Boolean":
- case "Object":
- case "Number":
- text = text.toLowerCase();
- break;
- case "array":
- case "date":
- case "promise":
- text = text[0].toUpperCase() + text.slice(1);
- break;
- }
- name = ts.createIdentifier(text);
- if ((text === "Array" || text === "Promise") && !node.typeArguments) {
- args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
- }
- else {
- args = ts.visitNodes(node.typeArguments, transformJSDocType);
- }
- }
- return ts.createTypeReferenceNode(name, args);
- }
- function transformJSDocIndexSignature(node) {
- var index = ts.createParameter(undefined, undefined, undefined, node.typeArguments[0].kind === 134 ? "n" : "s", undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 ? "number" : "string", []), undefined);
- var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(undefined, undefined, [index], node.typeArguments[1])]);
- ts.setEmitFlags(indexSignature, 1);
- return indexSignature;
- }
- })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var convertFunctionToES6Class;
- (function (convertFunctionToES6Class) {
- var refactorName = "Convert to ES2015 class";
- var actionName = "convert";
- var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (!ts.isInJavaScriptFile(context.file)) {
- return undefined;
- }
- var symbol = getConstructorSymbol(context);
- if (!symbol) {
- return undefined;
- }
- if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) {
- symbol = symbol.valueDeclaration.initializer.symbol;
- }
- if ((symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) {
- return [
- {
- name: refactorName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName
- }
- ]
- }
- ];
- }
- }
- function getEditsForAction(context, action) {
- if (actionName !== action) {
- return undefined;
- }
- var sourceFile = context.file;
- var ctorSymbol = getConstructorSymbol(context);
- var deletedNodes = [];
- var deletes = [];
- if (!(ctorSymbol.flags & (16 | 3))) {
- return undefined;
- }
- var ctorDeclaration = ctorSymbol.valueDeclaration;
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var precedingNode;
- var newClassDeclaration;
- switch (ctorDeclaration.kind) {
- case 232:
- precedingNode = ctorDeclaration;
- deleteNode(ctorDeclaration);
- newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
- break;
- case 230:
- precedingNode = ctorDeclaration.parent.parent;
- if (ctorDeclaration.parent.declarations.length === 1) {
- deleteNode(precedingNode);
- }
- else {
- deleteNode(ctorDeclaration, true);
- }
- newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
- break;
- }
- if (!newClassDeclaration) {
- return undefined;
- }
- changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
- for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) {
- var deleteCallback = deletes_1[_i];
- deleteCallback();
- }
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined,
- };
- function deleteNode(node, inList) {
- if (inList === void 0) { inList = false; }
- if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) {
- return;
- }
- deletedNodes.push(node);
- if (inList) {
- deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); });
- }
- else {
- deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); });
- }
- }
- function createClassElementsFromSymbol(symbol) {
- var memberElements = [];
- if (symbol.members) {
- symbol.members.forEach(function (member) {
- var memberElement = createClassElement(member, undefined);
- if (memberElement) {
- memberElements.push(memberElement);
- }
- });
- }
- if (symbol.exports) {
- symbol.exports.forEach(function (member) {
- var memberElement = createClassElement(member, [ts.createToken(115)]);
- if (memberElement) {
- memberElements.push(memberElement);
- }
- });
- }
- return memberElements;
- function shouldConvertDeclaration(_target, source) {
- return ts.isFunctionLike(source);
- }
- function createClassElement(symbol, modifiers) {
- if (!(symbol.flags & 4)) {
- return;
- }
- var memberDeclaration = symbol.valueDeclaration;
- var assignmentBinaryExpression = memberDeclaration.parent;
- if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
- return;
- }
- var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 214
- ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
- deleteNode(nodeToDelete);
- if (!assignmentBinaryExpression.right) {
- return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined);
- }
- switch (assignmentBinaryExpression.right.kind) {
- case 190: {
- var functionExpression = assignmentBinaryExpression.right;
- var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120));
- var method = ts.createMethod(undefined, fullModifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body);
- copyComments(assignmentBinaryExpression, method);
- return method;
- }
- case 191: {
- var arrowFunction = assignmentBinaryExpression.right;
- var arrowFunctionBody = arrowFunction.body;
- var bodyBlock = void 0;
- if (arrowFunctionBody.kind === 211) {
- bodyBlock = arrowFunctionBody;
- }
- else {
- bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
- }
- var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120));
- var method = ts.createMethod(undefined, fullModifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock);
- copyComments(assignmentBinaryExpression, method);
- return method;
- }
- default: {
- if (ts.isSourceFileJavaScript(sourceFile)) {
- return;
- }
- var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right);
- copyComments(assignmentBinaryExpression.parent, prop);
- return prop;
- }
- }
- }
- }
- function copyComments(sourceNode, targetNode) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
- if (kind === 3) {
- pos += 2;
- end -= 2;
- }
- else {
- pos += 2;
- }
- ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl);
- });
- }
- function createClassFromVariableDeclaration(node) {
- var initializer = node.initializer;
- if (!initializer || initializer.kind !== 190) {
- return undefined;
- }
- if (node.name.kind !== 71) {
- return undefined;
- }
- var memberElements = createClassElementsFromSymbol(initializer.symbol);
- if (initializer.body) {
- memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body));
- }
- var modifiers = getModifierKindFromSource(precedingNode, 84);
- var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements);
- return cls;
- }
- function createClassFromFunctionDeclaration(node) {
- var memberElements = createClassElementsFromSymbol(ctorSymbol);
- if (node.body) {
- memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body));
- }
- var modifiers = getModifierKindFromSource(node, 84);
- var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements);
- return cls;
- }
- function getModifierKindFromSource(source, kind) {
- return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
- }
- }
- function getConstructorSymbol(_a) {
- var startPosition = _a.startPosition, file = _a.file, program = _a.program;
- var checker = program.getTypeChecker();
- var token = ts.getTokenAtPosition(file, startPosition, false);
- return checker.getSymbolAtLocation(token);
- }
- })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var actionName = "Convert to ES6 module";
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module);
- refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- var file = context.file, startPosition = context.startPosition;
- if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) {
- return undefined;
- }
- var node = ts.getTokenAtPosition(file, startPosition, false);
- return !isAtTriggerLocation(file, node) ? undefined : [
- {
- name: actionName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function isAtTriggerLocation(sourceFile, node, onSecondTry) {
- if (onSecondTry === void 0) { onSecondTry = false; }
- switch (node.kind) {
- case 185:
- return isAtTopLevelRequire(node);
- case 183:
- return ts.isExportsOrModuleExportsOrAlias(sourceFile, node)
- || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression);
- case 231:
- return isVariableDeclarationTriggerLocation(ts.firstOrUndefined(node.declarations));
- case 230:
- return isVariableDeclarationTriggerLocation(node);
- default:
- return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node)
- || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, true);
- }
- function isVariableDeclarationTriggerLocation(decl) {
- return !!decl && !!decl.initializer && ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer);
- }
- }
- function isAtTopLevelRequire(call) {
- if (!ts.isRequireCall(call, true)) {
- return false;
- }
- var propAccess = call.parent;
- var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess;
- if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) {
- return true;
- }
- if (!ts.isVariableDeclaration(varDecl)) {
- return false;
- }
- var varDeclList = varDecl.parent;
- if (varDeclList.kind !== 231) {
- return false;
- }
- var varStatement = varDeclList.parent;
- return varStatement.kind === 212 && varStatement.parent.kind === 272;
- }
- function getEditsForAction(context, _actionName) {
- ts.Debug.assertEqual(actionName, _actionName);
- var file = context.file, program = context.program;
- ts.Debug.assert(ts.isSourceFileJavaScript(file));
- var edits = ts.textChanges.ChangeTracker.with(context, function (changes) {
- var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target);
- if (moduleExportsChangedToDefault) {
- for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
- var importingFile = _a[_i];
- fixImportOfModuleExports(importingFile, file, changes);
- }
- }
- });
- return { edits: edits, renameFilename: undefined, renameLocation: undefined };
- }
- function fixImportOfModuleExports(importingFile, exportingFile, changes) {
- for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
- var moduleSpecifier = _a[_i];
- var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
- if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
- continue;
- }
- var parent = moduleSpecifier.parent;
- switch (parent.kind) {
- case 252: {
- var importEq = parent.parent;
- changes.replaceNode(importingFile, importEq, makeImport(importEq.name, undefined, moduleSpecifier.text));
- break;
- }
- case 185: {
- var call = parent;
- if (ts.isRequireCall(call, false)) {
- changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default"));
- }
- break;
- }
- }
- }
- }
- function convertFileToEs6Module(sourceFile, checker, changes, target) {
- var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
- var exports = collectExportRenames(sourceFile, checker, identifiers);
- convertExportsAccesses(sourceFile, exports, changes);
- var moduleExportsChangedToDefault = false;
- for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
- var statement = _a[_i];
- var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports);
- moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
- }
- return moduleExportsChangedToDefault;
- }
- function collectExportRenames(sourceFile, checker, identifiers) {
- var res = ts.createMap();
- forEachExportReference(sourceFile, function (node) {
- var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
- if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
- || checker.resolveName(node.name.text, node, 107455, true))) {
- res.set(text, makeUniqueName("_" + text, identifiers));
- }
- });
- return res;
- }
- function convertExportsAccesses(sourceFile, exports, changes) {
- forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
- if (isAssignmentLhs) {
+ var codefix;
+ (function (codefix) {
+ var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
+ var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
+ var fixIdAddInitializer = "addMissingPropertyInitializer";
+ var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start);
+ if (!propertyDeclaration)
return;
- }
- var text = node.name.text;
- changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
- });
- }
- function forEachExportReference(sourceFile, cb) {
- sourceFile.forEachChild(function recur(node) {
- if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
- var parent = node.parent;
- cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58);
- }
- node.forEachChild(recur);
- });
- }
- function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) {
- switch (statement.kind) {
- case 212:
- convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target);
- return false;
- case 214: {
- var expression = statement.expression;
- switch (expression.kind) {
- case 185: {
- if (ts.isRequireCall(expression, true)) {
- changes.replaceNode(sourceFile, statement, makeImport(undefined, undefined, expression.arguments[0].text));
- }
- return false;
- }
- case 198: {
- var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
- return operatorToken.kind === 58 && convertAssignment(sourceFile, checker, statement, left, right, changes, exports);
- }
- }
- }
- default:
- return false;
- }
- }
- function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) {
- var declarationList = statement.declarationList;
- var foundImport = false;
- var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
- var name = decl.name, initializer = decl.initializer;
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
- foundImport = true;
- return [];
- }
- if (ts.isRequireCall(initializer, true)) {
- foundImport = true;
- return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target);
- }
- else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, true)) {
- foundImport = true;
- return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers);
- }
- else {
- return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
- }
- });
- if (foundImport) {
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- }
- }
- function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) {
- switch (name.kind) {
- case 178:
- case 179: {
- var tmp = makeUniqueName(propertyName, identifiers);
- return [
- makeSingleImport(tmp, propertyName, moduleSpecifier),
- makeConst(undefined, name, ts.createIdentifier(tmp)),
- ];
- }
- case 71:
- return [makeSingleImport(name.text, propertyName, moduleSpecifier)];
- default:
- ts.Debug.assertNever(name);
- }
- }
- function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) {
- if (!ts.isPropertyAccessExpression(left)) {
- return false;
- }
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
- changes.deleteNode(sourceFile, statement);
- }
- else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
- }
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- return changedToDefaultExport;
- }
- }
- else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
- convertNamedExport(sourceFile, statement, left.name, right, changes, exports);
- }
- return false;
- var _a;
- }
- function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
- switch (prop.kind) {
- case 155:
- case 156:
- case 269:
- case 270:
- return undefined;
- case 268:
- return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer);
- case 153:
- return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84)], prop);
- default:
- ts.Debug.assertNever(prop);
- }
- });
- }
- function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) {
- var text = propertyName.text;
- var rename = exports.get(text);
- if (rename !== undefined) {
- var newNodes = [
- makeConst(undefined, rename, right),
- makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
+ var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
+ var result = [
+ getActionForAddMissingUndefinedType(context, propertyDeclaration),
+ getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter)
];
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- }
- else {
- changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true });
- }
- }
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84), ts.createToken(79)];
- switch (exported.kind) {
- case 190:
- case 191: {
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 203: {
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 185:
- if (ts.isRequireCall(exported, true)) {
- return convertReExportAll(exported.arguments[0], checker);
+ ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter));
+ return result;
+ },
+ fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
+ getAllCodeActions: function (context) {
+ var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start);
+ if (!propertyDeclaration)
+ return;
+ switch (context.fixId) {
+ case fixIdAddDefiniteAssignmentAssertions:
+ addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration, newLineCharacter);
+ break;
+ case fixIdAddUndefinedType:
+ addUndefinedType(changes, diag.file, propertyDeclaration);
+ break;
+ case fixIdAddInitializer:
+ var checker = context.program.getTypeChecker();
+ var initializer = getInitializer(checker, propertyDeclaration);
+ if (!initializer)
+ return;
+ addInitializer(changes, diag.file, propertyDeclaration, initializer, newLineCharacter);
+ break;
+ default:
+ ts.Debug.fail(JSON.stringify(context.fixId));
}
- default:
- return [[ts.createExportAssignment(undefined, undefined, false, exported)], true];
+ });
+ },
+ });
+ function getPropertyDeclaration(sourceFile, pos) {
+ var token = ts.getTokenAtPosition(sourceFile, pos, false);
+ return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined;
+ }
+ function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter) {
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_definite_assignment_assertion_to_property_0), [propertyDeclaration.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration, newLineCharacter); });
+ return { description: description, changes: changes, fixId: fixIdAddDefiniteAssignmentAssertions };
+ }
+ function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, newLineCharacter) {
+ var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51), propertyDeclaration.type, propertyDeclaration.initializer);
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter });
+ }
+ function getActionForAddMissingUndefinedType(context, propertyDeclaration) {
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_undefined_type_to_property_0), [propertyDeclaration.name.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); });
+ return { description: description, changes: changes, fixId: fixIdAddUndefinedType };
+ }
+ function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
+ var undefinedTypeNode = ts.createKeywordTypeNode(140);
+ var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode];
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types));
+ }
+ function getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter) {
+ var checker = context.program.getTypeChecker();
+ var initializer = getInitializer(checker, propertyDeclaration);
+ if (!initializer)
+ return undefined;
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_initializer_to_property_0), [propertyDeclaration.name.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer, newLineCharacter); });
+ return { description: description, changes: changes, fixId: fixIdAddInitializer };
+ }
+ function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer, newLineCharacter) {
+ var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer);
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter });
+ }
+ function getInitializer(checker, propertyDeclaration) {
+ return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type));
+ }
+ function getDefaultValueFromType(checker, type) {
+ if (type.flags & 2) {
+ return ts.createLiteral("");
+ }
+ else if (type.flags & 4) {
+ return ts.createNumericLiteral("0");
+ }
+ else if (type.flags & 8) {
+ return ts.createFalse();
+ }
+ else if (type.flags & 224) {
+ return ts.createLiteral(type.value);
+ }
+ else if (type.flags & 131072) {
+ return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); });
+ }
+ else if (ts.getObjectFlags(type) & 1) {
+ var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
+ if (!classDeclaration || ts.hasModifier(classDeclaration, 128))
+ return undefined;
+ var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; });
+ if (constructorDeclaration && constructorDeclaration.parameters.length)
+ return undefined;
+ return ts.createNew(ts.createIdentifier(type.symbol.name), undefined, undefined);
+ }
+ return undefined;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "useDefaultImport";
+ var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, start = context.span.start;
+ var info = getInfo(sourceFile, start);
+ if (!info)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
+ return [{ description: description, changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var info = getInfo(diag.file, diag.start);
+ if (info)
+ doChange(changes, diag.file, info);
+ }); },
+ });
+ function getInfo(sourceFile, pos) {
+ var name = ts.getTokenAtPosition(sourceFile, pos, false);
+ if (!ts.isIdentifier(name))
+ return undefined;
+ var parent = name.parent;
+ if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) {
+ return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression };
+ }
+ else if (ts.isNamespaceImport(parent)) {
+ var importNode = parent.parent.parent;
+ return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier };
}
}
- function convertReExportAll(reExported, checker) {
- var moduleSpecifier = reExported.text;
- var moduleSymbol = checker.getSymbolAtLocation(reExported);
- var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
- return exports.has("export=")
- ? [[reExportDefault(moduleSpecifier)], true]
- : !exports.has("default")
- ? [[reExportStar(moduleSpecifier)], false]
- : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
+ function doChange(changes, sourceFile, info) {
+ changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, undefined, info.moduleSpecifier));
}
- function reExportStar(moduleSpecifier) {
- return makeExportDeclaration(undefined, moduleSpecifier);
- }
- function reExportDefault(moduleSpecifier) {
- return makeExportDeclaration([ts.createExportSpecifier(undefined, "default")], moduleSpecifier);
- }
- function convertExportsDotXEquals(name, exported) {
- var modifiers = [ts.createToken(84)];
- switch (exported.kind) {
- case 190: {
- var expressionName = exported.name;
- if (expressionName && expressionName.text !== name) {
- return exportConst();
- }
- }
- case 191:
- return functionExpressionToDeclaration(name, modifiers, exported);
- case 203:
- return classExpressionToDeclaration(name, modifiers, exported);
- default:
- return exportConst();
- }
- function exportConst() {
- return makeConst(modifiers, ts.createIdentifier(name), exported);
- }
- }
- function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) {
- switch (name.kind) {
- case 178: {
- var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) {
- return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name)
- ? undefined
- : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
- });
- if (importSpecifiers) {
- return [makeImport(undefined, importSpecifiers, moduleSpecifier)];
- }
- }
- case 179: {
- var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers);
- return [
- makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier),
- makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
- ];
- }
- case 71:
- return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers);
- default:
- ts.Debug.assertNever(name);
- }
- }
- function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) {
- var nameSymbol = checker.getSymbolAtLocation(name);
- var namedBindingsNames = ts.createMap();
- var needDefaultImport = false;
- for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
- var use = _a[_i];
- if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
- continue;
- }
- var parent = use.parent;
- if (ts.isPropertyAccessExpression(parent)) {
- var expression = parent.expression, propertyName = parent.name.text;
- ts.Debug.assert(expression === use);
- var idName = namedBindingsNames.get(propertyName);
- if (idName === undefined) {
- idName = makeUniqueName(propertyName, identifiers);
- namedBindingsNames.set(propertyName, idName);
- }
- changes.replaceNode(file, parent, ts.createIdentifier(idName));
- }
- else {
- needDefaultImport = true;
- }
- }
- var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
- var propertyName = _a[0], idName = _a[1];
- return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
- }));
- if (!namedBindings) {
- needDefaultImport = true;
- }
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
- }
- function makeUniqueName(name, identifiers) {
- while (identifiers.original.has(name) || identifiers.additional.has(name)) {
- name = "_" + name;
- }
- identifiers.additional.set(name, true);
- return name;
- }
- function collectFreeIdentifiers(file) {
- var map = ts.createMultiMap();
- file.forEachChild(function recur(node) {
- if (ts.isIdentifier(node) && isFreeIdentifier(node)) {
- map.add(node.text, node);
- }
- node.forEachChild(recur);
- });
- return map;
- }
- function isFreeIdentifier(node) {
- var parent = node.parent;
- switch (parent.kind) {
- case 183:
- return parent.name !== node;
- case 180:
- return parent.propertyName !== node;
- default:
- return true;
- }
- }
- function functionExpressionToDeclaration(name, additionalModifiers, fn) {
- return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
- }
- function classExpressionToDeclaration(name, additionalModifiers, cls) {
- return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
- }
- function makeSingleImport(localName, propertyName, moduleSpecifier) {
- return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier)
- : makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
- }
- function makeImport(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifier));
- }
- function makeImportSpecifier(propertyName, name) {
- return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
- }
- function makeConst(modifiers, name, init) {
- return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, undefined, init)], 2));
- }
- function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
- return ts.createExportDeclaration(undefined, undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
- }
- })(refactor = ts.refactor || (ts.refactor = {}));
+ })(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -81407,7 +81750,7 @@ var ts;
}
else if (ts.isVariableStatement(node)) {
var numInitializers = 0;
- var lastInitializer = undefined;
+ var lastInitializer = void 0;
for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (declaration.initializer) {
@@ -81514,7 +81857,7 @@ var ts;
switch (node.kind) {
case 232:
case 233:
- if (node.parent.kind === 272 && node.parent.externalModuleIndicator === undefined) {
+ if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
(errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
}
break;
@@ -81757,12 +82100,12 @@ var ts;
var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text);
var isJS = ts.isInJavaScriptFile(scope);
var functionName = ts.createIdentifier(functionNameText);
- var returnType = undefined;
+ var returnType;
var parameters = [];
var callArguments = [];
var writes;
usagesInScope.forEach(function (usage, name) {
- var typeNode = undefined;
+ var typeNode;
if (!isJS) {
var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
type = checker.getBaseTypeOfLiteralType(type);
@@ -81981,7 +82324,7 @@ var ts;
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function getContainingVariableDeclarationIfInList(node, scope) {
- var prevNode = undefined;
+ var prevNode;
while (node !== undefined && node !== scope) {
if (ts.isVariableDeclaration(node) &&
node.initializer === prevNode &&
@@ -82001,15 +82344,15 @@ var ts;
ts.Debug.assert(fileName === renameFilename);
for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) {
var change = textChanges_3[_b];
- var span_15 = change.span, newText = change.newText;
+ var span_14 = change.span, newText = change.newText;
var index = newText.indexOf(functionNameText);
if (index !== -1) {
- lastPos = span_15.start + delta + index;
+ lastPos = span_14.start + delta + index;
if (!isDeclaredBeforeUse) {
return lastPos;
}
}
- delta += newText.length - span_15.length;
+ delta += newText.length - span_14.length;
}
}
ts.Debug.assert(isDeclaredBeforeUse);
@@ -82017,7 +82360,7 @@ var ts;
return lastPos;
}
function getFirstDeclaration(type) {
- var firstDeclaration = undefined;
+ var firstDeclaration;
var symbol = type.symbol;
if (symbol && symbol.declarations) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
@@ -82131,7 +82474,7 @@ var ts;
function getNodeToInsertPropertyBefore(maxPos, scope) {
var members = scope.members;
ts.Debug.assert(members.length > 0);
- var prevMember = undefined;
+ var prevMember;
var allProperties = true;
for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
var member = members_6[_i];
@@ -82151,7 +82494,7 @@ var ts;
}
function getNodeToInsertConstantBefore(node, scope) {
ts.Debug.assert(!ts.isClassLike(scope));
- var prevScope = undefined;
+ var prevScope;
for (var curr = node; curr !== scope; curr = curr.parent) {
if (isScope(curr)) {
prevScope = curr;
@@ -82159,7 +82502,7 @@ var ts;
}
for (var curr = (prevScope || node).parent;; curr = curr.parent) {
if (isBlockLike(curr)) {
- var prevStatement = undefined;
+ var prevStatement = void 0;
for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) {
var statement = _a[_i];
if (statement.pos > node.pos) {
@@ -82211,13 +82554,13 @@ var ts;
var visibleDeclarationsInExtractedRange = [];
var exposedVariableSymbolSet = ts.createMap();
var exposedVariableDeclarations = [];
- var firstExposedNonVariableDeclaration = undefined;
+ var firstExposedNonVariableDeclaration;
var expression = !isReadonlyArray(targetRange.range)
? targetRange.range
: targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0])
? targetRange.range[0].expression
: undefined;
- var expressionDiagnostic = undefined;
+ var expressionDiagnostic;
if (expression === undefined) {
var statements = targetRange.range;
var start = ts.first(statements).getStart();
@@ -82283,14 +82626,14 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_10 = function (i) {
+ var _loop_11 = function (i) {
var scopeUsages = usagesPerScope[i];
if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range;
constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
}
var hasWrite = false;
- var readonlyClassPropertyWrite = undefined;
+ var readonlyClassPropertyWrite;
usagesPerScope[i].usages.forEach(function (value) {
if (value.usage === 2) {
hasWrite = true;
@@ -82319,7 +82662,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_10(i);
+ _loop_11(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function hasTypeParameters(node) {
@@ -82551,152 +82894,6 @@ var ts;
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var installTypesForPackage;
- (function (installTypesForPackage) {
- var refactorName = "Install missing types package";
- var actionName = "install";
- var description = "Install missing types package";
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) {
- return undefined;
- }
- var action = getAction(context);
- return action && [
- {
- name: refactorName,
- description: description,
- actions: [
- {
- description: action.description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function getEditsForAction(context, _actionName) {
- ts.Debug.assertEqual(actionName, _actionName);
- var action = getAction(context);
- return {
- edits: [],
- renameFilename: undefined,
- renameLocation: undefined,
- commands: action.commands,
- };
- }
- function getAction(context) {
- var file = context.file, startPosition = context.startPosition;
- var node = ts.getTokenAtPosition(file, startPosition, false);
- if (!ts.isStringLiteral(node) || !isModuleIdentifier(node)) {
- return undefined;
- }
- var resolvedTo = ts.getResolvedModule(file, node.text);
- if (resolvedTo && ts.extensionIsTypeScript(resolvedTo.extension)) {
- return undefined;
- }
- return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, file.fileName, node.text);
- }
- function isModuleIdentifier(node) {
- switch (node.parent.kind) {
- case 242:
- case 252:
- return true;
- default:
- return false;
- }
- }
- })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var installTypesForPackage;
- (function (installTypesForPackage) {
- var actionName = "Convert to default import";
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import);
- refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- var file = context.file, startPosition = context.startPosition, program = context.program;
- if (!ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
- return undefined;
- }
- var importInfo = getConvertibleImportAtPosition(file, startPosition);
- if (!importInfo) {
- return undefined;
- }
- var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
- if (!(resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) {
- return undefined;
- }
- return [
- {
- name: actionName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function getEditsForAction(context, _actionName) {
- var file = context.file, startPosition = context.startPosition;
- ts.Debug.assertEqual(actionName, _actionName);
- var importInfo = getConvertibleImportAtPosition(file, startPosition);
- if (!importInfo) {
- return undefined;
- }
- var importStatement = importInfo.importStatement, name = importInfo.name, moduleSpecifier = importInfo.moduleSpecifier;
- var newImportClause = ts.createImportClause(name, undefined);
- var newImportStatement = ts.createImportDeclaration(undefined, undefined, newImportClause, moduleSpecifier);
- return {
- edits: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, importStatement, newImportStatement); }),
- renameFilename: undefined,
- renameLocation: undefined,
- };
- }
- function getConvertibleImportAtPosition(file, startPosition) {
- var node = ts.getTokenAtPosition(file, startPosition, false);
- while (true) {
- switch (node.kind) {
- case 241:
- var eq = node;
- var moduleReference = eq.moduleReference;
- return moduleReference.kind === 252 && ts.isStringLiteral(moduleReference.expression)
- ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression }
- : undefined;
- case 242:
- var d = node;
- var importClause = d.importClause;
- return importClause && !importClause.name && importClause.namedBindings.kind === 244 && ts.isStringLiteral(d.moduleSpecifier)
- ? { importStatement: d, name: importClause.namedBindings.name, moduleSpecifier: d.moduleSpecifier }
- : undefined;
- case 244:
- case 252:
- case 91:
- case 71:
- case 9:
- case 39:
- break;
- default:
- return undefined;
- }
- node = node.parent;
- }
- }
- })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-var ts;
(function (ts) {
ts.servicesVersion = "0.7";
function createNode(kind, pos, end, parent) {
@@ -83191,20 +83388,8 @@ var ts;
}
function getDeclarationName(declaration) {
var name = ts.getNameOfDeclaration(declaration);
- if (name) {
- var result_6 = ts.getTextOfIdentifierOrLiteral(name);
- if (result_6 !== undefined) {
- return result_6;
- }
- if (name.kind === 146) {
- var expr = name.expression;
- if (expr.kind === 183) {
- return expr.name.text;
- }
- return ts.getTextOfIdentifierOrLiteral(expr);
- }
- }
- return undefined;
+ return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) :
+ name.kind === 146 && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined);
}
function visit(node) {
switch (node.kind) {
@@ -83690,6 +83875,10 @@ var ts;
var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
return semanticDiagnostics.concat(declarationDiagnostics);
}
+ function getSuggestionDiagnostics(fileName) {
+ synchronizeHostData();
+ return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program);
+ }
function getCompilerOptionsDiagnostics() {
synchronizeHostData();
return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken));
@@ -83714,41 +83903,39 @@ var ts;
if (node === sourceFile) {
return undefined;
}
- if (ts.isLabelName(node)) {
- return undefined;
- }
var typeChecker = program.getTypeChecker();
var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker);
if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
switch (node.kind) {
case 71:
+ if (ts.isLabelName(node)) {
+ return undefined;
+ }
case 183:
case 145:
case 99:
case 173:
case 97:
var type = typeChecker.getTypeAtLocation(node);
- if (type) {
- return {
- kind: "",
- kindModifiers: "",
- textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
- displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)),
- documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type.symbol ? type.symbol.getJsDocTags() : undefined
- };
- }
+ return type && {
+ kind: "",
+ kindModifiers: "",
+ textSpan: ts.createTextSpanFromNode(node, sourceFile),
+ displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)),
+ documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined,
+ tags: type.symbol ? type.symbol.getJsDocTags() : undefined
+ };
}
return undefined;
}
- var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node);
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags;
return {
- kind: displayPartsDocumentationsAndKind.symbolKind,
+ kind: symbolKind,
kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
- textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
- displayParts: displayPartsDocumentationsAndKind.displayParts,
- documentation: displayPartsDocumentationsAndKind.documentation,
- tags: displayPartsDocumentationsAndKind.tags
+ textSpan: ts.createTextSpanFromNode(node, sourceFile),
+ displayParts: displayParts,
+ documentation: documentation,
+ tags: tags,
};
}
function getSymbolAtLocationForQuickInfo(node, checker) {
@@ -83756,11 +83943,9 @@ var ts;
&& ts.isPropertyAssignment(node.parent)
&& node.parent.name === node) {
var type = checker.getContextualType(node.parent.parent);
- if (type) {
- var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node));
- if (property) {
- return property;
- }
+ var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node));
+ if (property) {
+ return property;
}
}
return checker.getSymbolAtLocation(node);
@@ -83997,7 +84182,7 @@ var ts;
ts.Debug.assert(scope.type === "file");
var sourceFile = getValidSourceFile(scope.fileName);
var formatContext = ts.formatting.getFormatContext(formatOptions);
- return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host);
+ return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program);
}
function applyCodeActionCommand(fileName, actionOrUndefined) {
var action = typeof fileName === "string" ? actionOrUndefined : fileName;
@@ -84061,7 +84246,7 @@ var ts;
if (!ts.isInComment(sourceFile, matchPosition)) {
continue;
}
- var descriptor = undefined;
+ var descriptor = void 0;
for (var i = 0; i < descriptors.length; i++) {
if (matchArray[i + firstDescriptorCaptureIndex]) {
descriptor = descriptors[i];
@@ -84132,6 +84317,7 @@ var ts;
cleanupSemanticCache: cleanupSemanticCache,
getSyntacticDiagnostics: getSyntacticDiagnostics,
getSemanticDiagnostics: getSemanticDiagnostics,
+ getSuggestionDiagnostics: getSuggestionDiagnostics,
getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics,
getSyntacticClassifications: getSyntacticClassifications,
getSemanticClassifications: getSemanticClassifications,
@@ -84234,20 +84420,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_7 = [];
+ var result_6 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_7.push(symbol);
+ result_6.push(symbol);
}
});
- return result_7;
+ return result_6;
}
if (symbol) {
- result_7.push(symbol);
- return result_7;
+ result_6.push(symbol);
+ return result_6;
}
}
return undefined;
@@ -84506,7 +84692,7 @@ var ts;
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
length: diagnostic.length,
- category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(diagnostic),
code: diagnostic.code
};
}
@@ -84546,7 +84732,7 @@ var ts;
};
LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) {
var newLine = ts.getNewLineOrDefaultFromHost(this.host);
- return ts.realizeDiagnostics(diagnostics, newLine);
+ return realizeDiagnostics(diagnostics, newLine);
};
LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) {
var _this = this;
@@ -84578,6 +84764,10 @@ var ts;
return _this.realizeDiagnostics(diagnostics);
});
};
+ LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) {
+ var _this = this;
+ return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); });
+ };
LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () {
var _this = this;
return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () {
@@ -85255,6 +85445,7 @@ var ts;
CommandTypes["GeterrForProject"] = "geterrForProject";
CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync";
CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync";
+ CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync";
CommandTypes["NavBar"] = "navbar";
CommandTypes["NavBarFull"] = "navbar-full";
CommandTypes["Navto"] = "navto";
@@ -85456,7 +85647,10 @@ var ts;
if (this.isOpen) {
return this.switchToScriptVersionCache();
}
- return !this.pendingReloadFromDisk && this.svc;
+ if (this.pendingReloadFromDisk) {
+ this.reloadWithFileText();
+ }
+ return this.svc;
};
TextStorage.prototype.getOrLoadText = function () {
if (this.text === undefined || this.pendingReloadFromDisk) {
@@ -85975,12 +86169,14 @@ var ts;
var filesWithChangedSetOfUnresolvedImports;
var filesWithInvalidatedResolutions;
var allFilesHaveInvalidatedResolution = false;
- var resolvedModuleNames = ts.createMap();
- var perDirectoryResolvedModuleNames = ts.createMap();
- var resolvedTypeReferenceDirectives = ts.createMap();
- var perDirectoryResolvedTypeReferenceDirectives = ts.createMap();
var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); });
var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
+ var resolvedModuleNames = ts.createMap();
+ var perDirectoryResolvedModuleNames = ts.createMap();
+ var nonRelaticeModuleNameCache = ts.createMap();
+ var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
+ var resolvedTypeReferenceDirectives = ts.createMap();
+ var perDirectoryResolvedTypeReferenceDirectives = ts.createMap();
var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"];
var customFailedLookupPaths = ts.createMap();
var directoryWatchesOfFailedLookups = ts.createMap();
@@ -86041,6 +86237,7 @@ var ts;
}
function clearPerDirectoryResolutions() {
perDirectoryResolvedModuleNames.clear();
+ nonRelaticeModuleNameCache.clear();
perDirectoryResolvedTypeReferenceDirectives.clear();
}
function finishCachingPerDirectoryResolution() {
@@ -86054,7 +86251,7 @@ var ts;
clearPerDirectoryResolutions();
}
function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host);
+ var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache);
if (!resolutionHost.getGlobalCache) {
return primaryResult;
}
@@ -86094,15 +86291,8 @@ var ts;
perDirectoryResolution.set(name, resolution);
}
resolutionsInFile.set(name, resolution);
- if (resolution.failedLookupLocations) {
- if (existingResolution && existingResolution.failedLookupLocations) {
- watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution);
- }
- else {
- watchFailedLookupLocationOfResolution(resolution, 0);
- }
- }
- else if (existingResolution) {
+ watchFailedLookupLocationOfResolution(resolution);
+ if (existingResolution) {
stopWatchFailedLookupLocationOfResolution(existingResolution);
}
if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
@@ -86197,69 +86387,87 @@ var ts;
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
}
- function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) {
- var failedLookupLocations = resolution.failedLookupLocations;
- var existingFailedLookupLocations = existingResolution.failedLookupLocations;
- for (var index = 0; index < failedLookupLocations.length; index++) {
- if (index === existingFailedLookupLocations.length) {
- watchFailedLookupLocationOfResolution(resolution, index);
- return;
- }
- else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) {
- watchFailedLookupLocationOfResolution(resolution, index);
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index);
- return;
- }
+ function watchFailedLookupLocationOfResolution(resolution) {
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length);
- }
- function watchFailedLookupLocationOfResolution(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ if (resolution.refCount !== undefined) {
+ resolution.refCount++;
+ return;
+ }
+ resolution.refCount = 1;
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var setAtRoot = false;
+ for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
- customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
- }
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore;
if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- if (dirWatcher) {
- dirWatcher.refCount++;
+ if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
+ }
+ if (dirPath === rootPath) {
+ setAtRoot = true;
}
else {
- directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ setDirectoryWatcher(dir, dirPath);
}
}
}
+ if (setAtRoot) {
+ setDirectoryWatcher(rootDir, rootPath);
+ }
+ }
+ function setDirectoryWatcher(dir, dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (dirWatcher) {
+ dirWatcher.refCount++;
+ }
+ else {
+ directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ }
}
function stopWatchFailedLookupLocationOfResolution(resolution) {
- if (resolution.failedLookupLocations) {
- stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0);
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- }
- function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ resolution.refCount--;
+ if (resolution.refCount) {
+ return;
+ }
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var removeAtRoot = false;
+ for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
- if (refCount) {
- if (refCount === 1) {
- customFailedLookupPaths.delete(failedLookupLocationPath);
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
+ if (!ignore) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
+ if (refCount) {
+ if (refCount === 1) {
+ customFailedLookupPaths.delete(failedLookupLocationPath);
+ }
+ else {
+ ts.Debug.assert(refCount > 1);
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ }
+ }
+ if (dirPath === rootPath) {
+ removeAtRoot = true;
}
else {
- ts.Debug.assert(refCount > 1);
- customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ removeDirectoryWatcher(dirPath);
}
}
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore;
- if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- dirWatcher.refCount--;
- }
}
+ if (removeAtRoot) {
+ removeDirectoryWatcher(rootPath);
+ }
+ }
+ function removeDirectoryWatcher(dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ dirWatcher.refCount--;
}
function createDirectoryWatcher(directory, dirPath) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
@@ -86827,6 +87035,7 @@ var ts;
server.isScriptInfo = isScriptInfo;
var Project = (function () {
function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) {
+ var _this = this;
this.projectName = projectName;
this.projectKind = projectKind;
this.projectService = projectService;
@@ -86845,6 +87054,7 @@ var ts;
this.hasChangedAutomaticTypeDirectiveNames = false;
this.directoryStructureHost = directoryStructureHost;
this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || "");
+ this.getCanonicalFileName = this.projectService.toCanonicalFileName;
this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds);
if (!this.compilerOptions) {
this.compilerOptions = ts.getDefaultCompilerOptions();
@@ -86856,7 +87066,10 @@ var ts;
}
this.setInternalCompilerOptionsForEmittingJsFiles();
var host = this.projectService.host;
- if (host.trace) {
+ if (this.projectService.logger.loggingEnabled()) {
+ this.trace = function (s) { return _this.writeLog(s); };
+ }
+ else if (host.trace) {
this.trace = function (s) { return host.trace(s); };
}
if (host.realpath) {
@@ -87437,8 +87650,8 @@ var ts;
var sourceFiles = this.program.getSourceFiles();
var strBuilder = "\tFiles (" + sourceFiles.length + ")\n";
if (writeProjectFileNames) {
- for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) {
- var file = sourceFiles_9[_i];
+ for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
+ var file = sourceFiles_7[_i];
strBuilder += "\t" + file.fileName + "\n";
}
}
@@ -87518,7 +87731,7 @@ var ts;
}
var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations);
if (this.projectService.globalPlugins) {
- var _loop_11 = function (globalPluginName) {
+ var _loop_12 = function (globalPluginName) {
if (!globalPluginName)
return "continue";
if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; }))
@@ -87529,7 +87742,7 @@ var ts;
var this_1 = this;
for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) {
var globalPluginName = _a[_i];
- _loop_11(globalPluginName);
+ _loop_12(globalPluginName);
}
}
};
@@ -88894,7 +89107,7 @@ var ts;
return projects;
function combineProjects(toAddInfo) {
if (toAddInfo !== info) {
- var _loop_12 = function (project) {
+ var _loop_13 = function (project) {
if (project.languageServiceEnabled &&
!project.getCompilerOptions().preserveSymlinks &&
!ts.contains(info.containingProjects, project)) {
@@ -88909,7 +89122,7 @@ var ts;
};
for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) {
var project = _a[_i];
- _loop_12(project);
+ _loop_13(project);
}
}
}
@@ -89136,13 +89349,13 @@ var ts;
this.printProjects();
};
ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
- var _loop_13 = function (proj) {
+ var _loop_14 = function (proj) {
var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; });
result.push(proj.getChangesSinceVersion(knownProject && knownProject.version));
};
for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) {
var proj = currentProjects_1[_i];
- _loop_13(proj);
+ _loop_14(proj);
}
};
ProjectService.prototype.synchronizeProjectList = function (knownProjects) {
@@ -89242,7 +89455,7 @@ var ts;
var excludeRules = [];
var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); });
var excludedFiles = [];
- var _loop_14 = function (name) {
+ var _loop_15 = function (name) {
var rule = this_2.safelist[name];
for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) {
var root = normalizedNames_1[_i];
@@ -89257,7 +89470,7 @@ var ts;
}
}
if (rule.exclude) {
- var _loop_15 = function (exclude) {
+ var _loop_16 = function (exclude) {
var processedRule = root.replace(rule.match, function () {
var groups = [];
for (var _i = 0; _i < arguments.length; _i++) {
@@ -89280,7 +89493,7 @@ var ts;
};
for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) {
var exclude = _d[_c];
- _loop_15(exclude);
+ _loop_16(exclude);
}
}
else {
@@ -89295,11 +89508,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_14(name);
+ _loop_15(name);
}
var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); });
var filesToKeep = [];
- var _loop_16 = function (i) {
+ var _loop_17 = function (i) {
if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) {
excludedFiles.push(normalizedNames[i]);
}
@@ -89333,7 +89546,7 @@ var ts;
};
var this_3 = this;
for (var i = 0; i < proj.rootFiles.length; i++) {
- _loop_16(i);
+ _loop_17(i);
}
proj.rootFiles = filesToKeep;
return excludedFiles;
@@ -89486,7 +89699,7 @@ var ts;
end: scriptInfo.positionToLineOffset(diag.start + diag.length),
text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"),
code: diag.code,
- category: ts.DiagnosticCategory[diag.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(diag),
source: diag.source
};
}
@@ -89498,7 +89711,7 @@ var ts;
var end = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length));
var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n");
var code = diag.code, source = diag.source;
- var category = ts.DiagnosticCategory[diag.category].toLowerCase();
+ var category = ts.diagnosticCategoryName(diag);
return includeFileName ? { start: start, end: end, text: text, code: code, category: category, source: source, fileName: diag.file && diag.file.fileName } :
{ start: start, end: end, text: text, code: code, category: category, source: source };
}
@@ -89791,6 +90004,9 @@ var ts;
_a[server.CommandNames.SyntacticDiagnosticsSync] = function (request) {
return _this.requiredResponse(_this.getSyntacticDiagnosticsSync(request.arguments));
},
+ _a[server.CommandNames.SuggestionDiagnosticsSync] = function (request) {
+ return _this.requiredResponse(_this.getSuggestionDiagnosticsSync(request.arguments));
+ },
_a[server.CommandNames.Geterr] = function (request) {
_this.errorCheck.startNew(function (next) { return _this.getDiagnostics(next, request.arguments.delay, request.arguments.files); });
return _this.notRequired();
@@ -90029,28 +90245,23 @@ var ts;
this.send(res);
};
Session.prototype.semanticCheck = function (file, project) {
- try {
- var diags = server.emptyArray;
- if (!isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) {
- diags = project.getLanguageService().getSemanticDiagnostics(file);
- }
- var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); });
- this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag");
- }
- catch (err) {
- this.logError(err, "semantic check");
- }
+ var diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file)
+ ? server.emptyArray
+ : project.getLanguageService().getSemanticDiagnostics(file);
+ this.sendDiagnosticsEvent(file, project, diags, "semanticDiag");
};
Session.prototype.syntacticCheck = function (file, project) {
+ this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag");
+ };
+ Session.prototype.infoCheck = function (file, project) {
+ this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag");
+ };
+ Session.prototype.sendDiagnosticsEvent = function (file, project, diagnostics, kind) {
try {
- var diags = project.getLanguageService().getSyntacticDiagnostics(file);
- if (diags) {
- var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); });
- this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag");
- }
+ this.event({ file: file, diagnostics: diagnostics.map(function (diag) { return formatDiag(file, project, diag); }) }, kind);
}
catch (err) {
- this.logError(err, "syntactic check");
+ this.logError(err, kind);
}
};
Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) {
@@ -90060,21 +90271,30 @@ var ts;
var followMs = Math.min(ms, 200);
var index = 0;
var checkOne = function () {
- if (_this.changeSeq === seq) {
- var checkSpec_1 = checkList[index];
- index++;
- if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) {
- _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project);
- if (_this.changeSeq === seq) {
- next.immediate(function () {
- _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project);
- if (checkList.length > index) {
- next.delay(followMs, checkOne);
- }
- });
- }
- }
+ if (_this.changeSeq !== seq) {
+ return;
}
+ var _a = checkList[index], fileName = _a.fileName, project = _a.project;
+ index++;
+ if (!project.containsFile(fileName, requireOpen)) {
+ return;
+ }
+ _this.syntacticCheck(fileName, project);
+ if (_this.changeSeq !== seq) {
+ return;
+ }
+ next.immediate(function () {
+ _this.semanticCheck(fileName, project);
+ if (_this.changeSeq !== seq) {
+ return;
+ }
+ next.immediate(function () {
+ _this.infoCheck(fileName, project);
+ if (checkList.length > index) {
+ next.delay(followMs, checkOne);
+ }
+ });
+ });
};
if (checkList.length > index && this.changeSeq === seq) {
next.delay(ms, checkOne);
@@ -90128,7 +90348,7 @@ var ts;
message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine),
start: d.start,
length: d.length,
- category: ts.DiagnosticCategory[d.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(d),
code: d.code,
startLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start)),
endLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length))
@@ -90144,7 +90364,7 @@ var ts;
message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine),
start: d.start,
length: d.length,
- category: ts.DiagnosticCategory[d.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(d),
code: d.code,
source: d.source,
startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start),
@@ -90270,6 +90490,13 @@ var ts;
}
return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition);
};
+ Session.prototype.getSuggestionDiagnosticsSync = function (args) {
+ var configFile = this.getConfigFileAndProject(args).configFile;
+ if (configFile) {
+ return server.emptyArray;
+ }
+ return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, args.includeLinePosition);
+ };
Session.prototype.getDocumentHighlights = function (args, simplifiedResult) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var position = this.getPositionInFile(args, file);
@@ -90726,12 +90953,12 @@ var ts;
return undefined;
}
if (simplifiedResult) {
- var span_16 = helpItems.applicableSpan;
+ var span_15 = helpItems.applicableSpan;
return {
items: helpItems.items,
applicableSpan: {
- start: scriptInfo.positionToLineOffset(span_16.start),
- end: scriptInfo.positionToLineOffset(span_16.start + span_16.length)
+ start: scriptInfo.positionToLineOffset(span_15.start),
+ end: scriptInfo.positionToLineOffset(span_15.start + span_15.length)
},
selectedItemIndex: helpItems.selectedItemIndex,
argumentIndex: helpItems.argumentIndex,
@@ -90917,7 +91144,7 @@ var ts;
return locationOrSpan.line !== undefined;
};
Session.prototype.extractPositionAndRange = function (args, scriptInfo) {
- var position = undefined;
+ var position;
var textRange;
if (this.isLocation(args)) {
position = getPosition(args);
@@ -91016,7 +91243,7 @@ var ts;
return {};
};
Session.prototype.getStartAndEndPosition = function (args, scriptInfo) {
- var startPosition = undefined, endPosition = undefined;
+ var startPosition, endPosition;
if (args.startPosition !== undefined) {
startPosition = args.startPosition;
}
diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts
index 8739616ce14..6763e768cda 100644
--- a/lib/tsserverlibrary.d.ts
+++ b/lib/tsserverlibrary.d.ts
@@ -1811,7 +1811,7 @@ declare namespace ts {
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined;
- getJsxIntrinsicTagNames(): Symbol[];
+ getJsxIntrinsicTagNamesAt(location: Node): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
@@ -2192,11 +2192,25 @@ declare namespace ts {
interface IndexType extends InstantiableType {
type: InstantiableType | UnionOrIntersectionType;
}
- interface ConditionalType extends InstantiableType {
+ interface ConditionalRoot {
+ node: ConditionalTypeNode;
checkType: Type;
extendsType: Type;
trueType: Type;
falseType: Type;
+ isDistributive: boolean;
+ inferTypeParameters: TypeParameter[];
+ outerTypeParameters?: TypeParameter[];
+ instantiations?: Map;
+ aliasSymbol: Symbol;
+ aliasTypeArguments: Type[];
+ }
+ interface ConditionalType extends InstantiableType {
+ root: ConditionalRoot;
+ checkType: Type;
+ extendsType: Type;
+ resolvedTrueType?: Type;
+ resolvedFalseType?: Type;
}
interface SubstitutionType extends InstantiableType {
typeParameter: TypeParameter;
@@ -2222,41 +2236,13 @@ declare namespace ts {
}
enum InferencePriority {
NakedTypeVariable = 1,
- MappedType = 2,
- ReturnType = 4,
- NoConstraints = 8,
- AlwaysStrict = 16,
+ HomomorphicMappedType = 2,
+ MappedTypeConstraint = 4,
+ ReturnType = 8,
+ NoConstraints = 16,
+ AlwaysStrict = 32,
+ PriorityImpliesUnion = 12,
}
- interface InferenceInfo {
- typeParameter: TypeParameter;
- candidates: Type[];
- contraCandidates: Type[];
- inferredType: Type;
- priority: InferencePriority;
- topLevel: boolean;
- isFixed: boolean;
- }
- enum InferenceFlags {
- None = 0,
- InferUnionTypes = 1,
- NoDefault = 2,
- AnyDefault = 4,
- }
- /**
- * Ternary values are defined such that
- * x & y is False if either x or y is False.
- * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
- * x & y is True if both x and y are True.
- * x | y is False if both x and y are False.
- * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
- * x | y is True if either x or y is True.
- */
- enum Ternary {
- False = 0,
- Maybe = 1,
- True = -1,
- }
- type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary;
interface JsFileExtensionInfo {
extension: string;
isMixedContent: boolean;
@@ -2292,7 +2278,8 @@ declare namespace ts {
enum DiagnosticCategory {
Warning = 0,
Error = 1,
- Message = 2,
+ Suggestion = 2,
+ Message = 3,
}
enum ModuleResolutionKind {
Classic = 1,
@@ -3246,7 +3233,8 @@ declare namespace ts {
function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression;
function isTemplateLiteral(node: Node): node is TemplateLiteral;
function isAssertionExpression(node: Node): node is AssertionExpression;
- function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement;
+ function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement;
+ function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement;
function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement;
function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause;
/** True if node is of a kind that may contain comment text. */
@@ -4084,6 +4072,7 @@ declare namespace ts {
cleanupSemanticCache(): void;
getSyntacticDiagnostics(fileName: string): Diagnostic[];
getSemanticDiagnostics(fileName: string): Diagnostic[];
+ getSuggestionDiagnostics(fileName: string): Diagnostic[];
getCompilerOptionsDiagnostics(): Diagnostic[];
/**
* @deprecated Use getEncodedSyntacticClassifications instead.
@@ -4494,7 +4483,7 @@ declare namespace ts {
argumentCount: number;
}
interface CompletionInfo {
- /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isGlobalCompletionScope`. */
+ /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */
isGlobalCompletion: boolean;
isMemberCompletion: boolean;
/**
@@ -4994,7 +4983,7 @@ declare namespace ts.server {
function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never;
}
function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings;
- function mergeMapLikes(target: MapLike, source: MapLike): void;
+ function mergeMapLikes(target: T, source: Partial): void;
type NormalizedPath = string & {
__normalizedPathTag: any;
};
@@ -5054,10 +5043,12 @@ declare namespace ts.server.protocol {
GeterrForProject = "geterrForProject",
SemanticDiagnosticsSync = "semanticDiagnosticsSync",
SyntacticDiagnosticsSync = "syntacticDiagnosticsSync",
+ SuggestionDiagnosticsSync = "suggestionDiagnosticsSync",
NavBar = "navbar",
Navto = "navto",
NavTree = "navtree",
NavTreeFull = "navtree-full",
+ /** @deprecated */
Occurrences = "occurrences",
DocumentHighlights = "documentHighlights",
Open = "open",
@@ -5658,6 +5649,7 @@ declare namespace ts.server.protocol {
openingBrace: string;
}
/**
+ * @deprecated
* Get occurrences request; value of command field is
* "occurrences". Return response giving spans that are relevant
* in the file at a given line and column.
@@ -5665,6 +5657,7 @@ declare namespace ts.server.protocol {
interface OccurrencesRequest extends FileLocationRequest {
command: CommandTypes.Occurrences;
}
+ /** @deprecated */
interface OccurrencesResponseItem extends FileSpan {
/**
* True if the occurrence is a write location, false otherwise.
@@ -5675,6 +5668,7 @@ declare namespace ts.server.protocol {
*/
isInString?: true;
}
+ /** @deprecated */
interface OccurrencesResponse extends Response {
body?: OccurrencesResponseItem[];
}
@@ -6572,6 +6566,12 @@ declare namespace ts.server.protocol {
interface SemanticDiagnosticsSyncResponse extends Response {
body?: Diagnostic[] | DiagnosticWithLinePosition[];
}
+ interface SuggestionDiagnosticsSyncRequest extends FileRequest {
+ command: CommandTypes.SuggestionDiagnosticsSync;
+ arguments: SuggestionDiagnosticsSyncRequestArgs;
+ }
+ type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs;
+ type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse;
/**
* Synchronous request for syntactic diagnostics of one file.
*/
@@ -6668,7 +6668,7 @@ declare namespace ts.server.protocol {
*/
text: string;
/**
- * The category of the diagnostic message, e.g. "error" vs. "warning"
+ * The category of the diagnostic message, e.g. "error", "warning", or "suggestion".
*/
category: string;
/**
@@ -6696,8 +6696,9 @@ declare namespace ts.server.protocol {
*/
diagnostics: Diagnostic[];
}
+ type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag";
/**
- * Event message for "syntaxDiag" and "semanticDiag" event types.
+ * Event message for DiagnosticEventKind event types.
* These events provide syntactic and semantic errors for a file.
*/
interface DiagnosticEvent extends Event {
@@ -7182,7 +7183,7 @@ declare namespace ts.server {
}
type CommandNames = protocol.CommandTypes;
const CommandNames: any;
- function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string;
+ function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string;
type Event = (body: T, eventName: string) => void;
interface EventSender {
event: Event;
@@ -7232,6 +7233,8 @@ declare namespace ts.server {
private doOutput(info, cmdName, reqSeq, success, message?);
private semanticCheck(file, project);
private syntacticCheck(file, project);
+ private infoCheck(file, project);
+ private sendDiagnosticsEvent(file, project, diagnostics, kind);
private updateErrorCheck(next, checkList, ms, requireOpen?);
private cleanProjects(caption, projects);
private cleanup();
@@ -7252,6 +7255,7 @@ declare namespace ts.server {
private getOccurrences(args);
private getSyntacticDiagnosticsSync(args);
private getSemanticDiagnosticsSync(args);
+ private getSuggestionDiagnosticsSync(args);
private getDocumentHighlights(args, simplifiedResult);
private setCompilerOptionsForInferredProjects(args);
private getProjectInfo(args);
diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js
index a75f0454587..f30d68c6b28 100644
--- a/lib/tsserverlibrary.js
+++ b/lib/tsserverlibrary.js
@@ -949,11 +949,14 @@ var ts;
var InferencePriority;
(function (InferencePriority) {
InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
- InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType";
- InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType";
- InferencePriority[InferencePriority["NoConstraints"] = 8] = "NoConstraints";
- InferencePriority[InferencePriority["AlwaysStrict"] = 16] = "AlwaysStrict";
+ InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
+ InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint";
+ InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType";
+ InferencePriority[InferencePriority["NoConstraints"] = 16] = "NoConstraints";
+ InferencePriority[InferencePriority["AlwaysStrict"] = 32] = "AlwaysStrict";
+ InferencePriority[InferencePriority["PriorityImpliesUnion"] = 12] = "PriorityImpliesUnion";
})(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
+ /* @internal */
var InferenceFlags;
(function (InferenceFlags) {
InferenceFlags[InferenceFlags["None"] = 0] = "None";
@@ -970,6 +973,7 @@ var ts;
* x | y is Maybe if either x or y is Maybe, but neither x or y is True.
* x | y is True if either x or y is True.
*/
+ /* @internal */
var Ternary;
(function (Ternary) {
Ternary[Ternary["False"] = 0] = "False";
@@ -995,8 +999,16 @@ var ts;
(function (DiagnosticCategory) {
DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
- DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message";
+ DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
+ DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
})(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
+ /* @internal */
+ function diagnosticCategoryName(d, lowerCase) {
+ if (lowerCase === void 0) { lowerCase = true; }
+ var name = DiagnosticCategory[d.category];
+ return lowerCase ? name.toLowerCase() : name;
+ }
+ ts.diagnosticCategoryName = diagnosticCategoryName;
var ModuleResolutionKind;
(function (ModuleResolutionKind) {
ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
@@ -1426,6 +1438,68 @@ var ts;
ListFormat[ListFormat["Parameters"] = 1296] = "Parameters";
ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters";
})(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
+ /* @internal */
+ var PragmaKindFlags;
+ (function (PragmaKindFlags) {
+ PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
+ /**
+ * Triple slash comment of the form
+ * ///
+ */
+ PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
+ /**
+ * Single line comment of the form
+ * // @pragma-name argval1 argval2
+ * or
+ * /// @pragma-name argval1 argval2
+ */
+ PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
+ /**
+ * Multiline non-jsdoc pragma of the form
+ * /* @pragma-name argval1 argval2 * /
+ */
+ PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
+ PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
+ PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
+ })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
+ /**
+ * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas`
+ */
+ /* @internal */
+ function _contextuallyTypePragmas(args) {
+ return args;
+ }
+ // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
+ // fancy effectively defining it twice, once in value-space and once in type-space
+ /* @internal */
+ ts.commentPragmas = _contextuallyTypePragmas({
+ "reference": {
+ args: [
+ { name: "types", optional: true, captureSpan: true },
+ { name: "path", optional: true, captureSpan: true },
+ { name: "no-default-lib", optional: true }
+ ],
+ kind: 1 /* TripleSlashXML */
+ },
+ "amd-dependency": {
+ args: [{ name: "path" }, { name: "name", optional: true }],
+ kind: 1 /* TripleSlashXML */
+ },
+ "amd-module": {
+ args: [{ name: "name" }],
+ kind: 1 /* TripleSlashXML */
+ },
+ "ts-check": {
+ kind: 2 /* SingleLine */
+ },
+ "ts-nocheck": {
+ kind: 2 /* SingleLine */
+ },
+ "jsx": {
+ args: [{ name: "factory" }],
+ kind: 4 /* MultiLine */
+ },
+ });
})(ts || (ts = {}));
/*@internal*/
var ts;
@@ -1528,7 +1602,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "2.8";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".0";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -2752,19 +2826,21 @@ var ts;
}
ts.equalOwnProperties = equalOwnProperties;
function arrayToMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = createMap();
for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
var value = array_6[_i];
- result.set(makeKey(value), makeValue ? makeValue(value) : value);
+ result.set(makeKey(value), makeValue(value));
}
return result;
}
ts.arrayToMap = arrayToMap;
function arrayToNumericMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = [];
for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
var value = array_7[_i];
- result[makeKey(value)] = makeValue ? makeValue(value) : value;
+ result[makeKey(value)] = makeValue(value);
}
return result;
}
@@ -2773,6 +2849,20 @@ var ts;
return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; });
}
ts.arrayToSet = arrayToSet;
+ function arrayToMultiMap(values, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
+ var result = createMultiMap();
+ for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
+ var value = values_1[_i];
+ result.add(makeKey(value), makeValue(value));
+ }
+ return result;
+ }
+ ts.arrayToMultiMap = arrayToMultiMap;
+ function group(values, getGroupId) {
+ return arrayFrom(arrayToMultiMap(values, getGroupId).values());
+ }
+ ts.group = group;
function cloneMap(map) {
var clone = createMap();
copyEntries(map, clone);
@@ -2830,15 +2920,6 @@ var ts;
}
}
}
- function group(values, getGroupId) {
- var groupIdToGroup = createMultiMap();
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- groupIdToGroup.add(getGroupId(value), value);
- }
- return arrayFrom(groupIdToGroup.values());
- }
- ts.group = group;
/**
* Tests whether a value is an array.
*/
@@ -2958,7 +3039,6 @@ var ts;
return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; });
}
ts.formatStringFromArgs = formatStringFromArgs;
- ts.localizedDiagnosticMessages = undefined;
function getLocaleSpecificMessage(message) {
return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
}
@@ -3884,7 +3964,7 @@ var ts;
// Sort the offsets array using either the literal or canonical path representations.
includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive);
var _loop_2 = function (includeBasePath) {
- if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
+ if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
basePaths.push(includeBasePath);
}
};
@@ -4289,7 +4369,7 @@ var ts;
ts.matchedText = matchedText;
/** Return the object corresponding to the best pattern to match `candidate`. */
function findBestPatternMatch(values, getPattern, candidate) {
- var matchedValue = undefined;
+ var matchedValue;
// use length of prefix as betterness criteria
var longestMatchPrefixLength = -1;
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
@@ -4393,7 +4473,7 @@ var ts;
*/
/* @internal */
function setStackTraceLimit() {
- if (Error.stackTraceLimit < 100) {
+ if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
Error.stackTraceLimit = 100;
}
}
@@ -4788,7 +4868,7 @@ var ts;
return stat.size;
}
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return 0;
},
exit: function (exitCode) {
@@ -5481,6 +5561,7 @@ var ts;
Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
+ Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
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}'."),
@@ -5552,7 +5633,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}'."),
- 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.Message, "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."),
+ 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}'."),
Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
@@ -5725,7 +5806,7 @@ var ts;
Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
- Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."),
+ Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
@@ -5769,6 +5850,7 @@ var ts;
Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."),
+ Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."),
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."),
@@ -5848,10 +5930,15 @@ var ts;
JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
+ JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
+ File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
+ This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
+ Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
+ JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
@@ -5892,6 +5979,9 @@ var ts;
Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
+ Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
+ Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
+ Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
};
})(ts || (ts = {}));
///
@@ -6286,8 +6376,7 @@ var ts;
}
ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
function isAmbientModule(node) {
- return node && node.kind === 237 /* ModuleDeclaration */ &&
- (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
+ return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
}
ts.isAmbientModule = isAmbientModule;
function isModuleWithStringLiteralName(node) {
@@ -6318,21 +6407,22 @@ var ts;
}
ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
function isExternalModuleAugmentation(node) {
+ return isAmbientModule(node) && isModuleAugmentationExternal(node);
+ }
+ ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ function isModuleAugmentationExternal(node) {
// external module augmentation is a ambient module declaration that is either:
// - 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
- if (!node || !isAmbientModule(node)) {
- return false;
- }
switch (node.parent.kind) {
case 272 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 238 /* ModuleBlock */:
- return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
+ return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
}
return false;
}
- ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
function isEffectiveExternalModule(node, compilerOptions) {
return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
}
@@ -7648,16 +7738,9 @@ var ts;
return false;
}
ts.isNodeDescendantOf = isNodeDescendantOf;
- // True if the given identifier, string literal, or number literal is the name of a declaration node
+ // True if `name` is the name of a declaration node
function isDeclarationName(name) {
- switch (name.kind) {
- case 71 /* Identifier */:
- case 9 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- return ts.isDeclaration(name.parent) && name.parent.name === name;
- default:
- return false;
- }
+ return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
}
ts.isDeclarationName = isDeclarationName;
// See GH#16030
@@ -7784,38 +7867,6 @@ var ts;
return undefined;
}
ts.getAncestor = getAncestor;
- function getFileReferenceFromReferencePath(comment, commentRange) {
- var simpleReferenceRegEx = /^\/\/\/\s*= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
}
ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
function textSpanIntersectsWith(span, start, length) {
- var end = start + length;
- return start <= textSpanEnd(span) && end >= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
}
ts.textSpanIntersectsWith = textSpanIntersectsWith;
function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
@@ -9485,12 +9524,9 @@ var ts;
}
ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
function textSpanIntersection(span1, span2) {
- var intersectStart = Math.max(span1.start, span2.start);
- var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
- if (intersectStart <= intersectEnd) {
- return createTextSpanFromBounds(intersectStart, intersectEnd);
- }
- return undefined;
+ var start = Math.max(span1.start, span2.start);
+ var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
+ return start <= end ? createTextSpanFromBounds(start, end) : undefined;
}
ts.textSpanIntersection = textSpanIntersection;
function createTextSpan(start, length) {
@@ -9755,6 +9791,7 @@ var ts;
return false;
}
try {
+ // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!)
ts.localizedDiagnosticMessages = JSON.parse(fileContents);
}
catch (e) {
@@ -11082,7 +11119,7 @@ var ts;
case 97 /* SuperKeyword */:
case 207 /* NonNullExpression */:
case 208 /* MetaProperty */:
- case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression
+ case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
return true;
default:
return false;
@@ -11167,7 +11204,6 @@ var ts;
|| isPartiallyEmittedExpression(node);
}
ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
- // Statement
function isIterationStatement(node, lookInLabeledStatements) {
switch (node.kind) {
case 218 /* ForStatement */:
@@ -14099,7 +14135,9 @@ var ts;
sourceFile.flags = contextFlags;
// Prime the scanner.
nextToken();
- processReferenceComments(sourceFile);
+ // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future
+ processCommentPragmas(sourceFile, sourceText);
+ processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
ts.Debug.assert(token() === 1 /* EndOfFileToken */);
sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
@@ -14112,6 +14150,9 @@ var ts;
fixupParentReferences(sourceFile);
}
return sourceFile;
+ function reportPragmaDiagnostic(pos, end, diagnostic) {
+ parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
+ }
}
function addJSDocComment(node) {
var comments = ts.getJSDocCommentRanges(node, sourceFile.text);
@@ -17089,8 +17130,9 @@ var ts;
var fullStart = scanner.getStartPos();
parseExpected(27 /* LessThanToken */);
if (token() === 29 /* GreaterThanToken */) {
- parseExpected(29 /* GreaterThanToken */);
+ // See below for explanation of scanJsxText
var node_1 = createNode(258 /* JsxOpeningFragment */, fullStart);
+ scanJsxText();
return finishNode(node_1);
}
var tagName = parseJsxElementName();
@@ -17137,7 +17179,9 @@ var ts;
}
function parseJsxExpression(inExpressionContext) {
var node = createNode(263 /* JsxExpression */);
- parseExpected(17 /* OpenBraceToken */);
+ if (!parseExpected(17 /* OpenBraceToken */)) {
+ return undefined;
+ }
if (token() !== 18 /* CloseBraceToken */) {
node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
node.expression = parseAssignmentExpressionOrHigher();
@@ -17332,7 +17376,7 @@ var ts;
case 48 /* AmpersandToken */: // foo &
case 49 /* BarToken */: // foo |
case 18 /* CloseBraceToken */: // foo }
- case 1 /* EndOfFileToken */:// foo
+ case 1 /* EndOfFileToken */: // foo
// these cases can't legally follow a type arg list. However, they're not legal
// expressions either. The user is probably in the middle of a generic type. So
// treat it as such.
@@ -17601,7 +17645,7 @@ var ts;
parseExpected(88 /* ForKeyword */);
var awaitToken = parseOptionalToken(121 /* AwaitKeyword */);
parseExpected(19 /* OpenParenToken */);
- var initializer = undefined;
+ var initializer;
if (token() !== 25 /* SemicolonToken */) {
if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) {
initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
@@ -18302,7 +18346,7 @@ var ts;
case 51 /* ExclamationToken */: // Non-null assertion on property name
case 56 /* ColonToken */: // Type Annotation for declaration
case 58 /* EqualsToken */: // Initializer for declaration
- case 55 /* QuestionToken */:// Not valid, but permitted so that it gets caught later on.
+ case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
return true;
default:
// Covers
@@ -18617,7 +18661,7 @@ var ts;
// import ModuleSpecifier;
if (identifier || // import id
token() === 39 /* AsteriskToken */ || // import *
- token() === 17 /* OpenBraceToken */) {
+ token() === 17 /* OpenBraceToken */) { // import {
node.importClause = parseImportClause(identifier, afterImportPos);
parseExpected(142 /* FromKeyword */);
}
@@ -18767,87 +18811,6 @@ var ts;
parseSemicolon();
return finishNode(node);
}
- function processReferenceComments(sourceFile) {
- var triviaScanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText);
- var referencedFiles = [];
- var typeReferenceDirectives = [];
- var amdDependencies = [];
- var amdModuleName;
- var checkJsDirective = undefined;
- // Keep scanning all the leading trivia in the file until we get to something that
- // isn't trivia. Any single line comment will be analyzed to see if it is a
- // reference comment.
- while (true) {
- var kind = triviaScanner.scan();
- if (kind !== 2 /* SingleLineCommentTrivia */) {
- if (ts.isTrivia(kind)) {
- continue;
- }
- else {
- break;
- }
- }
- var range = {
- kind: triviaScanner.getToken(),
- pos: triviaScanner.getTokenPos(),
- end: triviaScanner.getTextPos(),
- };
- var comment = sourceText.substring(range.pos, range.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range);
- if (referencePathMatchResult) {
- var fileReference = referencePathMatchResult.fileReference;
- sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var diagnosticMessage = referencePathMatchResult.diagnosticMessage;
- if (fileReference) {
- if (referencePathMatchResult.isTypeReferenceDirective) {
- typeReferenceDirectives.push(fileReference);
- }
- else {
- referencedFiles.push(fileReference);
- }
- }
- if (diagnosticMessage) {
- parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage));
- }
- }
- else {
- var amdModuleNameRegEx = /^\/\/\/\s* context.checkJsDirective.pos) {
+ context.checkJsDirective = {
+ enabled: key === "ts-check",
+ end: entry.range.end,
+ pos: entry.range.pos
+ };
+ }
+ });
+ break;
+ }
+ case "jsx": return; // Accessed directly
+ default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
+ }
+ });
+ }
+ ts.processPragmasIntoFields = processPragmasIntoFields;
+ var namedArgRegExCache = ts.createMap();
+ function getNamedArgRegEx(name) {
+ if (namedArgRegExCache.has(name)) {
+ return namedArgRegExCache.get(name);
+ }
+ var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
+ namedArgRegExCache.set(name, result);
+ return result;
+ }
+ var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
+ var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
+ function extractPragmas(pragmas, range, text) {
+ var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text);
+ if (tripleSlash) {
+ var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
+ return;
+ }
+ if (pragma.args) {
+ var argument = {};
+ for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
+ var arg = _a[_i];
+ var matcher = getNamedArgRegEx(arg.name);
+ var matchResult = matcher.exec(text);
+ if (!matchResult && !arg.optional) {
+ return; // Missing required argument, don't parse
+ }
+ else if (matchResult) {
+ if (arg.captureSpan) {
+ var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
+ argument[arg.name] = {
+ value: matchResult[3],
+ pos: startPos,
+ end: startPos + matchResult[3].length
+ };
+ }
+ else {
+ argument[arg.name] = matchResult[3];
+ }
+ }
+ }
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ }
+ else {
+ pragmas.push({ name: name, args: { arguments: {}, range: range } });
+ }
+ return;
+ }
+ var singleLine = singleLinePragmaRegEx.exec(text);
+ if (singleLine) {
+ return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
+ }
+ var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
+ var multiLineMatch;
+ while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
+ addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
+ }
+ }
+ function addPragmaForMatch(pragmas, range, kind, match) {
+ if (!match)
+ return;
+ var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & kind)) {
+ return;
+ }
+ var args = match[2]; // Split on spaces and match up positionally with definition
+ var argument = getNamedPragmaArguments(pragma, args);
+ if (argument === "fail")
+ return; // Missing required argument, fail to parse it
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ return;
+ }
+ function getNamedPragmaArguments(pragma, text) {
+ if (!text)
+ return {};
+ if (!pragma.args)
+ return {};
+ var args = text.split(/\s+/);
+ var argMap = {};
+ for (var i = 0; i < pragma.args.length; i++) {
+ var argument = pragma.args[i];
+ if (!args[i] && !argument.optional) {
+ return "fail";
+ }
+ if (argument.captureSpan) {
+ return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
+ }
+ argMap[argument.name] = args[i];
+ }
+ return argMap;
+ }
})(ts || (ts = {}));
///
///
@@ -20125,6 +20291,13 @@ var ts;
category: ts.Diagnostics.Command_line_Options,
description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
},
+ {
+ name: "preserveWatchOutput",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
+ },
{
name: "watch",
shortName: "w",
@@ -20206,9 +20379,10 @@ var ts;
"es2017.string": "lib.es2017.string.d.ts",
"es2017.intl": "lib.es2017.intl.d.ts",
"es2017.typedarrays": "lib.es2017.typedarrays.d.ts",
+ "es2018.promise": "lib.es2018.promise.d.ts",
+ "es2018.regexp": "lib.es2018.regexp.d.ts",
"esnext.array": "lib.esnext.array.d.ts",
"esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
- "esnext.promise": "lib.esnext.promise.d.ts",
}),
},
showInSimplifiedHelpView: true,
@@ -22076,7 +22250,7 @@ var ts;
for (var key in opts) {
if (opts.hasOwnProperty(key)) {
var type = getOptionFromName(key);
- if (type !== undefined) {
+ if (type !== undefined) { // Ignore unknown options
out[key] = getOptionValueWithEmptyStrings(opts[key], type);
}
}
@@ -22086,11 +22260,11 @@ var ts;
ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
function getOptionValueWithEmptyStrings(value, option) {
switch (option.type) {
- case "object":// "paths". Can't get any useful information from the value since we blank out strings, so just return "".
+ case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
return "";
- case "string":// Could be any arbitrary string -- use empty string instead.
+ case "string": // Could be any arbitrary string -- use empty string instead.
return "";
- case "number":// Allow numbers, but be sure to check it's actually a number.
+ case "number": // Allow numbers, but be sure to check it's actually a number.
return typeof value === "number" ? value : "";
case "boolean":
return typeof value === "boolean" ? value : "";
@@ -22351,8 +22525,11 @@ var ts;
}
ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
- var directoryToModuleNameMap = ts.createMap();
- var moduleNameToDirectoryMap = ts.createMap();
+ return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName);
+ }
+ ts.createModuleResolutionCache = createModuleResolutionCache;
+ /*@internal*/
+ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
function getOrCreateCacheForDirectory(directoryName) {
var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
@@ -22436,7 +22613,7 @@ var ts;
}
}
}
- ts.createModuleResolutionCache = createModuleResolutionCache;
+ ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
@@ -22447,7 +22624,7 @@ var ts;
var result = perFolderCache && perFolderCache.get(moduleName);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
}
else {
@@ -22637,7 +22814,7 @@ var ts;
trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
}
// string is for exact match
- var matchedPattern = undefined;
+ var matchedPattern;
if (state.compilerOptions.paths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
@@ -22913,7 +23090,7 @@ var ts;
var packageJsonPath = pathToPackageJson(nodeModuleDirectory);
if (directoryExists && host.fileExists(packageJsonPath)) {
var packageJsonContent = readJson(packageJsonPath, host);
- if (subModuleName === "") {
+ if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName
var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state);
if (typeof path === "string") {
subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1));
@@ -23009,7 +23186,7 @@ var ts;
}
else {
var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
- if (rest !== "") {
+ if (rest !== "") { // If "rest" is empty, we just did this search above.
var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName);
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId.
packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId;
@@ -23086,6 +23263,7 @@ var ts;
return "@types/" + getMangledNameForScopedPackage(packageName);
}
ts.getTypesPackageName = getTypesPackageName;
+ /* @internal */
function getMangledNameForScopedPackage(packageName) {
if (ts.startsWith(packageName, "@")) {
var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
@@ -23095,6 +23273,7 @@ var ts;
}
return packageName;
}
+ ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage;
/* @internal */
function getPackageNameFromAtTypesDirectory(mangledName) {
var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
@@ -23115,7 +23294,7 @@ var ts;
var result = cache && cache.get(containingDirectory);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
}
@@ -23421,7 +23600,7 @@ var ts;
ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
}
- return ts.getEscapedTextOfIdentifierOrLiteral(name);
+ return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
switch (node.kind) {
case 154 /* Constructor */:
@@ -23562,7 +23741,12 @@ var ts;
}
}
addDeclarationToSymbol(symbol, node, includes);
- symbol.parent = parent;
+ if (symbol.parent) {
+ ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ symbol.parent = parent;
+ }
return symbol;
}
function declareModuleMember(node, symbolFlags, symbolExcludes) {
@@ -24651,7 +24835,7 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
- if (ts.isExternalModuleAugmentation(node)) {
+ if (ts.isModuleAugmentationExternal(node)) {
declareModuleSymbol(node);
}
else {
@@ -24666,9 +24850,7 @@ var ts;
}
}
var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
- if (pattern) {
- (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol });
- }
+ file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
}
}
else {
@@ -25073,7 +25255,7 @@ var ts;
seenThisKeyword = true;
return;
case 160 /* TypePredicate */:
- return checkTypePredicate(node);
+ break; // Binding the children will handle everything
case 147 /* TypeParameter */:
return bindTypeParameter(node);
case 148 /* Parameter */:
@@ -25197,16 +25379,6 @@ var ts;
function bindAnonymousTypeWorker(node) {
return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
}
- function checkTypePredicate(node) {
- var parameterName = node.parameterName, type = node.type;
- if (parameterName && parameterName.kind === 71 /* Identifier */) {
- checkStrictModeIdentifier(parameterName);
- }
- if (parameterName && parameterName.kind === 173 /* ThisType */) {
- seenThisKeyword = true;
- }
- bind(type);
- }
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (ts.isExternalModule(file)) {
@@ -26873,7 +27045,7 @@ var ts;
node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement);
return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined;
},
- getJsxIntrinsicTagNames: getJsxIntrinsicTagNames,
+ getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
isOptionalParameter: function (node) {
node = ts.getParseTreeNode(node, ts.isParameter);
return node ? isOptionalParameter(node) : false;
@@ -26912,7 +27084,7 @@ var ts;
resolveName: function (name, location, meaning, excludeGlobals) {
return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
},
- getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); },
+ getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
@@ -26924,13 +27096,13 @@ var ts;
node = ts.getParseTreeNode(node, ts.isTypeNode);
return node && getTypeArgumentConstraint(node);
},
+ getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; },
};
var tupleTypes = [];
var unionTypes = ts.createMap();
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
- var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4 /* Property */, "unknown");
@@ -26999,6 +27171,7 @@ var ts;
var anyArrayType;
var autoArrayType;
var anyReadonlyArrayType;
+ var deferredGlobalNonNullableTypeAlias;
// The library files are only loaded when the feature is used.
// 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
@@ -27015,9 +27188,6 @@ var ts;
var deferredGlobalAsyncIteratorType;
var deferredGlobalAsyncIterableIteratorType;
var deferredGlobalTemplateStringsArrayType;
- var deferredJsxElementClassType;
- var deferredJsxElementType;
- var deferredJsxStatelessElementType;
var deferredNodes;
var deferredUnusedIdentifierNodes;
var flowLoopStart = 0;
@@ -27044,6 +27214,19 @@ var ts;
var potentialNewTargetCollisions = [];
var awaitedTypeStack = [];
var diagnostics = ts.createDiagnosticCollection();
+ // Suggestion diagnostics must have a file. Keyed by source file name.
+ var suggestionDiagnostics = ts.createMultiMap();
+ function addSuggestionDiagnostic(diag) {
+ suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
+ }
+ function addErrorOrSuggestionDiagnostic(isError, diag) {
+ if (isError) {
+ diagnostics.add(diag);
+ }
+ else {
+ addSuggestionDiagnostic(diag);
+ }
+ }
var TypeFacts;
(function (TypeFacts) {
TypeFacts[TypeFacts["None"] = 0] = "None";
@@ -27069,8 +27252,7 @@ var ts;
TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull";
TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy";
TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy";
- TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable";
- TypeFacts[TypeFacts["All"] = 8388607] = "All";
+ TypeFacts[TypeFacts["All"] = 4194303] = "All";
// The following members encode facts about particular kinds of types for use in the getTypeFacts function.
// The presence of a particular fact means that the given test is true for some (and possibly all) values
// of that kind of type.
@@ -27100,10 +27282,10 @@ var ts;
TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts";
TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts";
TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts";
- TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts";
- TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts";
- TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts";
- TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts";
+ TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts";
+ TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts";
+ TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts";
+ TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts";
TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts";
TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts";
})(TypeFacts || (TypeFacts = {}));
@@ -27135,12 +27317,6 @@ var ts;
var typeofType = createTypeofType();
var _jsxNamespace;
var _jsxFactoryEntity;
- var _jsxElementPropertiesName;
- var _hasComputedJsxElementPropertiesName = false;
- var _jsxElementChildrenPropertyName;
- var _hasComputedJsxElementChildrenPropertyName = false;
- /** Things we lazy load from the JSX namespace */
- var jsxTypes = ts.createUnderscoreEscapedMap();
var subtypeRelation = ts.createMap();
var assignableRelation = ts.createMap();
var definitelyAssignableRelation = ts.createMap();
@@ -27196,6 +27372,7 @@ var ts;
TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType";
TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject";
TypeIncludes[TypeIncludes["Union"] = 2048] = "Union";
+ TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard";
})(TypeIncludes || (TypeIncludes = {}));
var MembersOrExportsResolutionKind;
(function (MembersOrExportsResolutionKind) {
@@ -27343,7 +27520,23 @@ var ts;
};
}
}
- function getJsxNamespace() {
+ function getJsxNamespace(location) {
+ if (location) {
+ var file = ts.getSourceFileOfNode(location);
+ if (file) {
+ if (file.localJsxNamespace) {
+ return file.localJsxNamespace;
+ }
+ var jsxPragma = file.pragmas.get("jsx");
+ if (jsxPragma) {
+ var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
+ file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
+ if (file.localJsxFactory) {
+ return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
+ }
+ }
+ }
+ }
if (!_jsxNamespace) {
_jsxNamespace = "React";
if (compilerOptions.jsxFactory) {
@@ -28027,7 +28220,7 @@ var ts;
case 234 /* InterfaceDeclaration */:
case 236 /* EnumDeclaration */:
case 235 /* TypeAliasDeclaration */:
- case 237 /* ModuleDeclaration */:// For `namespace N { N; }`
+ case 237 /* ModuleDeclaration */: // For `namespace N { N; }`
return true;
default:
return false;
@@ -28339,7 +28532,15 @@ var ts;
combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
symbolFromModule || symbolFromVariable;
if (!symbol) {
- error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name));
+ var moduleName = getFullyQualifiedName(moduleSymbol);
+ var declarationName = ts.declarationNameToString(name);
+ var suggestion = getSuggestionForNonexistentModule(name, targetSymbol);
+ if (suggestion !== undefined) {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion);
+ }
+ else {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
+ }
}
return symbol;
}
@@ -28550,6 +28751,9 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
+ if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) {
+ addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
+ }
// merged symbol is module declaration symbol combined with all augmentations
return getMergedSymbol(sourceFile.symbol);
}
@@ -28571,10 +28775,8 @@ var ts;
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
}
- else if (noImplicitAny && moduleNotFoundError) {
- var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name);
- errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName);
- diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo));
+ else {
+ addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
}
// Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
return undefined;
@@ -28597,6 +28799,12 @@ var ts;
}
return undefined;
}
+ function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) {
+ var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
+ var errorInfo = packageId && ts.chainDiagnosticMessages(
+ /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name));
+ return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
+ }
// An external module with an 'export =' declaration resolves to the target of the 'export =' declaration,
// and an external module with no 'export =' declaration resolves to the module itself.
function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
@@ -28874,11 +29082,19 @@ var ts;
// If we are looking in value space, the parent meaning is value, other wise it is namespace
return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */;
}
- function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) {
+ function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
+ if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
return undefined;
}
- var visitedSymbolTables = [];
+ var id = "" + getSymbolId(symbol);
+ var visitedSymbolTables;
+ if (visitedSymbolTablesMap.has(id)) {
+ visitedSymbolTables = visitedSymbolTablesMap.get(id);
+ }
+ else {
+ visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
+ }
return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
/**
* @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)
@@ -28895,7 +29111,7 @@ var ts;
// If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
// If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
- !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing);
+ !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
}
function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) &&
@@ -28913,7 +29129,8 @@ var ts;
// Check if symbol is any of the alias
return ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
if (symbolFromSymbolTable.flags & 2097152 /* Alias */
- && symbolFromSymbolTable.escapedName !== "export="
+ && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
+ && symbolFromSymbolTable.escapedName !== "default" /* Default */
&& !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
// If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
&& (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) {
@@ -29150,6 +29367,7 @@ var ts;
}
}
function typeToString(type, enclosingDeclaration, flags, writer) {
+ if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer);
ts.Debug.assert(typeNode !== undefined, "should always get typenode");
@@ -29275,6 +29493,9 @@ var ts;
}
if (type.flags & 1024 /* UniqueESSymbol */) {
if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
+ if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
+ return ts.createTypeQueryNode(symbolToName(type.symbol, context, 107455 /* Value */, /*expectsIdentifier*/ false));
+ }
if (context.tracker.reportInaccessibleUniqueSymbolError) {
context.tracker.reportInaccessibleUniqueSymbolError();
}
@@ -29357,8 +29578,8 @@ var ts;
if (type.flags & 2097152 /* Conditional */) {
var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
- var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
- var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
+ var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
+ var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
if (type.flags & 4194304 /* Substitution */) {
@@ -29527,7 +29748,7 @@ var ts;
}
}
}
- var entityName = undefined;
+ var entityName = void 0;
var nameIdentifier = symbolToTypeReferenceName(type.symbol);
if (qualifiedName) {
ts.Debug.assert(!qualifiedName.right);
@@ -29981,8 +30202,8 @@ var ts;
return "(Anonymous function)";
}
}
- if (symbol.syntheticLiteralTypeOrigin) {
- var stringValue = symbol.syntheticLiteralTypeOrigin.value;
+ if (symbol.nameType && symbol.nameType.flags & 32 /* StringLiteral */) {
+ var stringValue = symbol.nameType.value;
if (!ts.isIdentifierText(stringValue, compilerOptions.target)) {
return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\"";
}
@@ -30290,7 +30511,7 @@ var ts;
parentType = getNonNullableType(parentType);
}
var propType = getTypeOfPropertyOfType(parentType, text);
- var declaredType = propType && getApparentTypeForLocation(propType, declaration.name);
+ var declaredType = propType && getConstraintForLocation(propType, declaration.name);
type = declaredType && getFlowTypeOfReference(declaration, declaredType) ||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
getIndexTypeOfType(parentType, 0 /* String */);
@@ -30722,6 +30943,7 @@ var ts;
if (getter && getter.body) {
type = getReturnTypeFromBody(getter);
}
+ // Otherwise, fall back to 'any'.
else {
if (noImplicitAny) {
if (setter) {
@@ -31593,8 +31815,18 @@ var ts;
error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3);
lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */);
}
+ var symbolLinks_1 = getSymbolLinks(lateSymbol);
+ if (!symbolLinks_1.nameType) {
+ // Retain link to name type so that it can be reused later
+ symbolLinks_1.nameType = type;
+ }
addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
- lateSymbol.parent = parent;
+ if (lateSymbol.parent) {
+ ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ lateSymbol.parent = parent;
+ }
return links.resolvedSymbol = lateSymbol;
}
}
@@ -31796,7 +32028,7 @@ var ts;
}
return [signature];
}
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
// Allow matching non-generic signatures to have excess parameters and different return types
var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true);
@@ -31813,7 +32045,7 @@ var ts;
// type is the union of the constituent return types.
function getUnionSignatures(types, kind) {
var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); });
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
var signature = _a[_i];
@@ -31944,7 +32176,7 @@ var ts;
else {
// Combinations of function, class, enum and module
var members = emptySymbols;
- var stringIndexInfo = undefined;
+ var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
}
@@ -32043,13 +32275,12 @@ var ts;
// Create a mapper from T to the current iteration type constituent. Then, if the
// mapped type is itself an instantiated type, combine the iteration mapper with the
// instantiation mapper.
- var iterationMapper = createTypeMapper([typeParameter], [t]);
- var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper;
+ var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t]));
var propType = instantiateType(templateType, templateMapper);
// If the current iteration type constituent is a string literal type, create a property.
// Otherwise, for type string create a string index signature.
if (t.flags & 32 /* StringLiteral */) {
- var propName = ts.escapeLeadingUnderscores(t.value);
+ var propName = getLateBoundNameFromType(t);
var modifiersProp = getPropertyOfType(modifiersType, propName);
var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
!(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
@@ -32066,7 +32297,7 @@ var ts;
prop.syntheticOrigin = propertySymbol;
prop.declarations = propertySymbol.declarations;
}
- prop.syntheticLiteralTypeOrigin = t;
+ prop.nameType = t;
members.set(propName, prop);
}
else if (t.flags & (1 /* Any */ | 2 /* String */)) {
@@ -32251,7 +32482,7 @@ var ts;
return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined;
}
function getDefaultConstraintOfConditionalType(type) {
- return getUnionType([type.trueType, type.falseType]);
+ return getUnionType([getTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]);
}
function getConstraintOfDistributiveConditionalType(type) {
// Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
@@ -32259,13 +32490,11 @@ var ts;
// with its constraint. We do this because if the constraint is a union type it will be distributed
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
- if (isDistributiveConditionalType(type)) {
+ if (type.root.isDistributive) {
var constraint = getConstraintOfType(type.checkType);
if (constraint) {
- var target = type.target || type;
- var mapper = createTypeMapper([target.checkType], [constraint]);
- var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper;
- return instantiateType(target, combinedMapper);
+ var mapper = createTypeMapper([type.root.checkType], [constraint]);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
}
}
return undefined;
@@ -32273,17 +32502,27 @@ var ts;
function getConstraintOfConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
- function getBaseConstraintOfType(type) {
+ function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) {
if (type.flags & (7372800 /* InstantiableNonPrimitive */ | 393216 /* UnionOrIntersection */)) {
var constraint = getResolvedBaseConstraint(type);
if (constraint !== noConstraintType && constraint !== circularConstraintType) {
return constraint;
}
}
- else if (type.flags & 524288 /* Index */) {
+ }
+ function getBaseConstraintOfType(type) {
+ var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type);
+ if (!constraint && type.flags & 524288 /* Index */) {
return stringType;
}
- return undefined;
+ return constraint;
+ }
+ /**
+ * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
+ * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
+ */
+ function getBaseConstraintOrType(type) {
+ return getBaseConstraintOfType(type) || type;
}
function hasNonCircularBaseConstraint(type) {
return getResolvedBaseConstraint(type) !== circularConstraintType;
@@ -32347,7 +32586,8 @@ var ts;
return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 2097152 /* Conditional */) {
- return getBaseConstraint(getConstraintOfConditionalType(t));
+ var constraint = getConstraintOfConditionalType(t);
+ return constraint && getBaseConstraint(constraint);
}
if (t.flags & 4194304 /* Substitution */) {
return getBaseConstraint(t.substitute);
@@ -32458,7 +32698,7 @@ var ts;
}
var propTypes = [];
var declarations = [];
- var commonType = undefined;
+ var commonType;
for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
var prop = props_1[_b];
if (prop.declarations) {
@@ -32715,7 +32955,7 @@ var ts;
var parameters = [];
var hasLiteralTypes = false;
var minArgumentCount = 0;
- var thisParameter = undefined;
+ var thisParameter = void 0;
var hasThisParameter = void 0;
var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
@@ -33242,6 +33482,7 @@ var ts;
if (ts.isEntityNameExpression(expr)) {
return expr;
}
+ // fall through;
}
return undefined;
}
@@ -33497,15 +33738,6 @@ var ts;
var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined);
return symbol && getTypeOfGlobalSymbol(symbol, arity);
}
- /**
- * Returns a type that is inside a namespace at the global scope, e.g.
- * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type
- */
- function getExportedTypeFromNamespace(namespace, name) {
- var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined);
- var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */);
- return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol);
- }
/**
* Instantiates a global type that is generic with some element type, and returns that instantiation.
*/
@@ -33617,6 +33849,8 @@ var ts;
}
else if (flags & 1 /* Any */) {
includes |= 1 /* Any */;
+ if (type === wildcardType)
+ includes |= 4096 /* Wildcard */;
}
else if (!strictNullChecks && flags & 12288 /* Nullable */) {
if (flags & 4096 /* Undefined */)
@@ -33737,7 +33971,7 @@ var ts;
var typeSet = [];
var includes = addTypesToUnion(typeSet, 0, types);
if (includes & 1 /* Any */) {
- return anyType;
+ return includes & 4096 /* Wildcard */ ? wildcardType : anyType;
}
switch (unionReduction) {
case 1 /* Literal */:
@@ -33830,6 +34064,8 @@ var ts;
}
else if (flags & 1 /* Any */) {
includes |= 1 /* Any */;
+ if (type === wildcardType)
+ includes |= 4096 /* Wildcard */;
}
else if (flags & 16384 /* Never */) {
includes |= 8 /* Never */;
@@ -33880,7 +34116,7 @@ var ts;
return neverType;
}
if (includes & 1 /* Any */) {
- return anyType;
+ return includes & 4096 /* Wildcard */ ? wildcardType : anyType;
}
if (includes & 1024 /* EmptyObject */ && !(includes & 512 /* ObjectType */)) {
typeSet.push(emptyObjectType);
@@ -33922,19 +34158,30 @@ var ts;
return type.resolvedIndexType;
}
function getLiteralTypeFromPropertyName(prop) {
- return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ?
- neverType :
- getLiteralType(ts.symbolName(prop));
+ var links = getSymbolLinks(prop);
+ if (!links.nameType) {
+ if (links.target) {
+ ts.Debug.assert(links.target.escapedName === prop.escapedName, "Target symbol and symbol do not have the same name");
+ links.nameType = getLiteralTypeFromPropertyName(links.target);
+ }
+ else {
+ links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ?
+ neverType :
+ getLiteralType(ts.symbolName(prop));
+ }
+ }
+ return links.nameType;
}
function getLiteralTypeFromPropertyNames(type) {
return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName));
}
function getIndexType(type) {
- return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) :
- ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) :
- type === wildcardType ? wildcardType :
- type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType :
- getLiteralTypeFromPropertyNames(type);
+ return type.flags & 262144 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) :
+ maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) :
+ ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) :
+ type === wildcardType ? wildcardType :
+ type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType :
+ getLiteralTypeFromPropertyNames(type);
}
function getIndexTypeOrString(type) {
var indexType = getIndexType(type);
@@ -34095,10 +34342,13 @@ var ts;
}
function substituteIndexedMappedType(objectType, type) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper;
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
}
function getIndexedAccessType(objectType, indexType, accessNode) {
+ if (objectType === wildcardType || indexType === wildcardType) {
+ return wildcardType;
+ }
// If the index type is generic, or if the object type is generic and doesn't originate in an expression,
// we are performing a higher-order index access where we cannot meaningfully access the properties of the
// object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
@@ -34158,73 +34408,62 @@ var ts;
function getActualTypeParameter(type) {
return type.flags & 4194304 /* Substitution */ ? type.typeParameter : type;
}
- function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) {
- var type = createType(2097152 /* Conditional */);
- type.checkType = checkType;
- type.extendsType = extendsType;
- type.trueType = trueType;
- type.falseType = falseType;
- type.inferTypeParameters = inferTypeParameters;
- type.target = target;
- type.mapper = mapper;
- type.aliasSymbol = aliasSymbol;
- type.aliasTypeArguments = aliasTypeArguments;
- return type;
- }
- function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) {
- // Instantiate extends type without instantiating any 'infer T' type parameters
- var extendsType = instantiateType(baseExtendsType, mapper);
- // Return falseType for a definitely false extends check. We check an instantations 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 instatiations will be and we can just return the false branch type.
- if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) {
- return instantiateType(baseFalseType, mapper);
+ function getConditionalType(root, mapper) {
+ var checkType = instantiateType(root.checkType, mapper);
+ var extendsType = instantiateType(root.extendsType, mapper);
+ if (checkType === wildcardType || extendsType === wildcardType) {
+ return wildcardType;
}
- // The check could be true for some instantiation
- var combinedMapper;
- if (inferTypeParameters) {
- var inferences = ts.map(inferTypeParameters, createInferenceInfo);
- // 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(inferences, checkType, extendsType, 8 /* NoConstraints */ | 16 /* AlwaysStrict */);
- // We infer 'never' when there are no candidates for a type parameter
- var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; });
- var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes);
- combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper;
- }
- // Return union of trueType and falseType for any and never since they match anything
- if (checkType.flags & 1 /* Any */ || (checkType.flags & 16384 /* Never */ && !(extendsType.flags & 16384 /* Never */))) {
- return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]);
- }
- // Instantiate the extends type including inferences for 'infer T' type parameters
- var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType;
- // Return trueType for a definitely true extends check. The definitely assignable relation excludes
- // type variable constraints from consideration. Without the definitely assignable relation, the type
- // type Foo = T extends { x: string } ? string : number
- // would immediately resolve to 'string' instead of being deferred.
- if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) {
- return instantiateType(baseTrueType, combinedMapper || mapper);
+ // If this is a distributive conditional type and the check type is generic we need to defer
+ // resolution of the conditional type such that a later instantiation will properly distribute
+ // over union types.
+ if (!root.isDistributive || !maybeTypeOfKind(checkType, 7897088 /* Instantiable */)) {
+ var combinedMapper = void 0;
+ if (root.inferTypeParameters) {
+ var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
+ // 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, 16 /* NoConstraints */ | 32 /* AlwaysStrict */);
+ combinedMapper = combineTypeMappers(mapper, context);
+ }
+ // Return union of trueType and falseType for 'any' since it matches anything
+ if (checkType.flags & 1 /* Any */) {
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ }
+ // Instantiate the extends type including inferences for 'infer T' type parameters
+ var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
+ // Return falseType for a definitely false extends check. We check an instantations 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 instatiations will be and we can just return the false branch type.
+ if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) {
+ return instantiateType(root.falseType, mapper);
+ }
+ // Return trueType for a definitely true extends check. The definitely assignable relation excludes
+ // type variable constraints from consideration. Without the definitely assignable relation, the type
+ // type Foo = T extends { x: string } ? string : number
+ // would immediately resolve to 'string' instead of being deferred.
+ if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) {
+ return instantiateType(root.trueType, combinedMapper || mapper);
+ }
}
// Return a deferred type for a check that is neither definitely true nor definitely false
var erasedCheckType = getActualTypeParameter(checkType);
- var trueType = instantiateType(baseTrueType, mapper);
- var falseType = instantiateType(baseFalseType, mapper);
- // We compute the cache key from the ids of the four constituent types, plus an indicator of whether the
- // type is distributive (i.e. whether the original declaration has a type parameter as the check type).
- var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 /* TypeParameter */ ? 1 : 0;
- var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive;
- var cached = conditionalTypes.get(id);
- if (cached) {
- return cached;
- }
- var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper));
- conditionalTypes.set(id, result);
+ var result = createType(2097152 /* Conditional */);
+ result.root = root;
+ result.checkType = erasedCheckType;
+ result.extendsType = extendsType;
+ result.mapper = mapper;
+ result.aliasSymbol = root.aliasSymbol;
+ result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper);
return result;
}
- function isDistributiveConditionalType(type) {
- return !!((type.target || type).checkType.flags & 32768 /* TypeParameter */);
+ function getTrueTypeFromConditionalType(type) {
+ return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
+ }
+ function getFalseTypeFromConditionalType(type) {
+ return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -34240,7 +34479,28 @@ var ts;
function getTypeFromConditionalTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), /*target*/ undefined, /*mapper*/ undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node));
+ var checkType = getTypeFromTypeNode(node.checkType);
+ var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
+ var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
+ var root = {
+ node: node,
+ checkType: checkType,
+ extendsType: getTypeFromTypeNode(node.extendsType),
+ trueType: getTypeFromTypeNode(node.trueType),
+ falseType: getTypeFromTypeNode(node.falseType),
+ isDistributive: !!(checkType.flags & 32768 /* TypeParameter */),
+ inferTypeParameters: getInferTypeParameters(node),
+ outerTypeParameters: outerTypeParameters,
+ instantiations: undefined,
+ aliasSymbol: getAliasSymbolForTypeNode(node),
+ aliasTypeArguments: aliasTypeArguments
+ };
+ links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
+ if (outerTypeParameters) {
+ root.instantiations = ts.createMap();
+ root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
+ }
}
return links.resolvedType;
}
@@ -34585,14 +34845,18 @@ var ts;
return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
}
function isInferenceContext(mapper) {
- return !!mapper.signature;
+ return !!mapper.typeParameters;
}
function cloneTypeMapper(mapper) {
return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
+ createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
mapper;
}
function combineTypeMappers(mapper1, mapper2) {
+ if (!mapper1)
+ return mapper2;
+ if (!mapper2)
+ return mapper1;
return function (t) { return instantiateType(mapper1(t), mapper2); };
}
function createReplacementMapper(source, target, baseMapper) {
@@ -34774,22 +35038,35 @@ var ts;
return result;
}
function getConditionalTypeInstantiation(type, mapper) {
- var target = type.target || type;
- var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper;
+ 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, mapper);
+ var id = getTypeListId(typeArguments);
+ var result = root.instantiations.get(id);
+ if (!result) {
+ var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
+ result = instantiateConditionalType(root, newMapper);
+ root.instantiations.set(id, result);
+ }
+ return result;
+ }
+ return type;
+ }
+ function instantiateConditionalType(root, mapper) {
// 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).
- if (isDistributiveConditionalType(target)) {
- var checkType_1 = target.checkType;
- var instantiatedType = combinedMapper(checkType_1);
- if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072 /* Union */) {
- return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); });
+ if (root.isDistributive) {
+ var checkType_1 = root.checkType;
+ var instantiatedType = mapper(checkType_1);
+ if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 /* Union */ | 16384 /* Never */)) {
+ return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); });
}
}
- return instantiateConditionalType(target, combinedMapper);
- }
- function instantiateConditionalType(type, mapper) {
- return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments);
+ return getConditionalType(root, mapper);
}
function instantiateType(type, mapper) {
if (type && mapper && mapper !== identityMapper) {
@@ -34830,7 +35107,7 @@ var ts;
return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
}
if (type.flags & 2097152 /* Conditional */) {
- return getConditionalTypeInstantiation(type, mapper);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (type.flags & 4194304 /* Substitution */) {
return mapper(type.typeParameter);
@@ -35503,11 +35780,11 @@ var ts;
}
}
if (flags & 2097152 /* Conditional */) {
- if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
- if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) {
+ if (source.root.isDistributive === target.root.isDistributive) {
+ if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
+ if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
+ if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
return result;
}
}
@@ -35895,20 +36172,11 @@ var ts;
}
}
else if (source.flags & 2097152 /* Conditional */) {
- if (relation !== definitelyAssignableRelation) {
- var constraint = getConstraintOfDistributiveConditionalType(source);
- if (constraint) {
- if (result = isRelatedTo(constraint, target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
- }
- }
- }
if (target.flags & 2097152 /* Conditional */) {
if (isTypeIdenticalTo(source.checkType, target.checkType) &&
isTypeIdenticalTo(source.extendsType, target.extendsType)) {
- if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
- result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
+ if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
+ result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -35916,9 +36184,21 @@ var ts;
}
}
}
- else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
+ else if (relation !== definitelyAssignableRelation) {
+ var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
+ if (distributiveConstraint) {
+ if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ var defaultConstraint = getDefaultConstraintOfConditionalType(source);
+ if (defaultConstraint) {
+ if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
}
}
else {
@@ -36783,8 +37063,18 @@ var ts;
ts.Debug.assert(strictNullChecks);
return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]);
}
+ function getGlobalNonNullableTypeInstantiation(type) {
+ 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, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higherorder behavior
+ }
function getNonNullableType(type) {
- return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type;
+ return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
}
/**
* Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
@@ -36886,6 +37176,10 @@ var ts;
}
var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name);
result.type = undefinedType;
+ var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (associatedKeyType.flags & 32 /* StringLiteral */) {
+ result.nameType = associatedKeyType;
+ }
undefinedProperties.set(name, result);
return result;
}
@@ -37049,9 +37343,10 @@ var ts;
callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
}
}
- function createInferenceContext(signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo);
+ function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
+ var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(typeParameters, createInferenceInfo);
var context = mapper;
+ context.typeParameters = typeParameters;
context.signature = signature;
context.inferences = inferences;
context.flags = flags;
@@ -37170,7 +37465,7 @@ var ts;
var templateType = getTemplateTypeFromMappedType(target);
var inference = createInferenceInfo(typeParameter);
inferTypes([inference], sourceType, templateType);
- return getTypeFromInference(inference) || emptyObjectType;
+ return getTypeFromInference(inference);
}
function getUnmatchedProperty(source, target, requireOptionalProperties) {
var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
@@ -37188,18 +37483,29 @@ var ts;
function getTypeFromInference(inference) {
return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
- undefined;
+ emptyObjectType;
}
function inferTypes(inferences, originalSource, originalTarget, priority) {
if (priority === void 0) { priority = 0; }
var symbolStack;
var visited;
var contravariant = false;
+ var propagationType;
inferFromTypes(originalSource, originalTarget);
function inferFromTypes(source, target) {
if (!couldContainTypeVariables(target)) {
return;
}
+ if (source.flags & 1 /* Any */) {
+ // We are inferring from an 'any' type. We want to infer this type for every type parameter
+ // referenced in the target type, so we record it as the propagation type and infer from the
+ // target to itself. Then, as we find candidates we substitute the propagation type.
+ var savePropagationType = propagationType;
+ propagationType = source;
+ inferFromTypes(target, target);
+ propagationType = savePropagationType;
+ return;
+ }
if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
// Source and target are types originating in the same generic type alias declaration.
// Simply infer from source type arguments to target type arguments.
@@ -37269,14 +37575,15 @@ var ts;
inference.priority = priority;
}
if (priority === inference.priority) {
+ var candidate = propagationType || source;
if (contravariant) {
- inference.contraCandidates = ts.append(inference.contraCandidates, source);
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
}
else {
- inference.candidates = ts.append(inference.candidates, source);
+ inference.candidates = ts.append(inference.candidates, candidate);
}
}
- if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
}
}
@@ -37316,8 +37623,8 @@ var ts;
else if (source.flags & 2097152 /* Conditional */ && target.flags & 2097152 /* Conditional */) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(source.trueType, target.trueType);
- inferFromTypes(source.falseType, target.falseType);
+ inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
+ inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
}
else if (target.flags & 393216 /* UnionOrIntersection */) {
var targetTypes = target.types;
@@ -37353,7 +37660,7 @@ var ts;
}
}
else {
- if (!(priority && 8 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) {
+ if (!(priority & 16 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) {
source = getApparentType(source);
}
if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) {
@@ -37384,7 +37691,7 @@ var ts;
}
}
function inferFromContravariantTypes(source, target) {
- if (strictFunctionTypes || priority & 16 /* AlwaysStrict */) {
+ if (strictFunctionTypes || priority & 32 /* AlwaysStrict */) {
contravariant = !contravariant;
inferFromTypes(source, target);
contravariant = !contravariant;
@@ -37423,7 +37730,7 @@ var ts;
var inferredType = inferTypeForHomomorphicMappedType(source, target);
if (inferredType) {
var savePriority = priority;
- priority |= 2 /* MappedType */;
+ priority |= 2 /* HomomorphicMappedType */;
inferFromTypes(inferredType, inference.typeParameter);
priority = savePriority;
}
@@ -37433,7 +37740,10 @@ var ts;
if (constraintType.flags & 32768 /* TypeParameter */) {
// We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
// parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
+ var savePriority = priority;
+ priority |= 4 /* MappedTypeConstraint */;
inferFromTypes(getIndexType(source), constraintType);
+ priority = savePriority;
inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target));
return;
}
@@ -37542,58 +37852,63 @@ var ts;
var inference = context.inferences[index];
var inferredType = inference.inferredType;
if (!inferredType) {
- if (inference.candidates) {
- // Extract all object literal types and replace them with a single widened and normalized type.
- var candidates = widenObjectLiteralCandidates(inference.candidates);
- // We widen inferred literal types if
- // all inferences were made to top-level ocurrences of the type parameter, and
- // the type parameter has no constraint or its constraint includes no primitive or literal types, and
- // the type parameter was fixed during inference or does not occur at top-level in the return type.
- var signature = context.signature;
- var widenLiteralTypes = inference.topLevel &&
- !hasPrimitiveConstraint(inference.typeParameter) &&
- (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
- var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
- // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if
- // union types were requested or if all inferences were made from the return type position, infer a
- // union type. Otherwise, infer a common supertype.
- var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ?
- getUnionType(baseCandidates, 2 /* Subtype */) :
- getCommonSupertype(baseCandidates);
- inferredType = getWidenedType(unwidenedType);
- // If we have inferred 'never' but have contravariant candidates. To get a more specific type we
- // infer from the contravariant candidates instead.
- if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) {
+ var signature = context.signature;
+ if (signature) {
+ if (inference.candidates) {
+ // Extract all object literal types and replace them with a single widened and normalized type.
+ var candidates = widenObjectLiteralCandidates(inference.candidates);
+ // We widen inferred literal types if
+ // all inferences were made to top-level ocurrences of the type parameter, and
+ // the type parameter has no constraint or its constraint includes no primitive or literal types, and
+ // the type parameter was fixed during inference or does not occur at top-level in the return type.
+ var widenLiteralTypes = inference.topLevel &&
+ !hasPrimitiveConstraint(inference.typeParameter) &&
+ (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
+ var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
+ // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if
+ // union types were requested or if all inferences were made from the return type position, infer a
+ // union type. Otherwise, infer a common supertype.
+ var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 12 /* PriorityImpliesUnion */ ?
+ getUnionType(baseCandidates, 2 /* Subtype */) :
+ getCommonSupertype(baseCandidates);
+ inferredType = getWidenedType(unwidenedType);
+ // If we have inferred 'never' but have contravariant candidates. To get a more specific type we
+ // infer from the contravariant candidates instead.
+ if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) {
+ inferredType = getCommonSubtype(inference.contraCandidates);
+ }
+ }
+ else if (inference.contraCandidates) {
+ // We only have contravariant inferences, infer the best common subtype of those
inferredType = getCommonSubtype(inference.contraCandidates);
}
- }
- else if (inference.contraCandidates) {
- // We only have contravariant inferences, infer the best common subtype of those
- inferredType = getCommonSubtype(inference.contraCandidates);
- }
- else if (context.flags & 2 /* NoDefault */) {
- // We use silentNeverType as the wildcard that signals no inferences.
- inferredType = silentNeverType;
- }
- else {
- // Infer either the default or the empty object type when no inferences were
- // made. It is important to remember that in this case, inference still
- // succeeds, meaning there is no error for not having inference candidates. An
- // inference error only occurs when there are *conflicting* candidates, i.e.
- // candidates with no common supertype.
- var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
- if (defaultType) {
- // Instantiate the default type. Any forward reference to a type
- // parameter should be instantiated to the empty object type.
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ else if (context.flags & 2 /* NoDefault */) {
+ // We use silentNeverType as the wildcard that signals no inferences.
+ inferredType = silentNeverType;
}
else {
- inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */));
+ // Infer either the default or the empty object type when no inferences were
+ // made. It is important to remember that in this case, inference still
+ // succeeds, meaning there is no error for not having inference candidates. An
+ // inference error only occurs when there are *conflicting* candidates, i.e.
+ // candidates with no common supertype.
+ var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
+ if (defaultType) {
+ // Instantiate the default type. Any forward reference to a type
+ // parameter should be instantiated to the empty object type.
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ }
+ else {
+ inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */));
+ }
}
}
+ else {
+ inferredType = getTypeFromInference(inference);
+ }
inferredType = getWidenedUniqueESSymbolType(inferredType);
inference.inferredType = inferredType;
- var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]);
+ var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
var instantiatedConstraint = instantiateType(constraint, context);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
@@ -37638,7 +37953,7 @@ var ts;
function getFlowCacheKey(node) {
if (node.kind === 71 /* Identifier */) {
var symbol = getResolvedSymbol(node);
- return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
+ return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
}
if (node.kind === 99 /* ThisKeyword */) {
return "0";
@@ -37857,8 +38172,8 @@ var ts;
}
if (flags & 65536 /* Object */) {
return isFunctionObjectType(type) ?
- strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ :
- strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */;
+ strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ :
+ strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */;
}
if (flags & (2048 /* Void */ | 4096 /* Undefined */)) {
return 2457472 /* UndefinedFacts */;
@@ -37870,7 +38185,7 @@ var ts;
return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */;
}
if (flags & 134217728 /* NonPrimitive */) {
- return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */;
+ return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */;
}
if (flags & 7897088 /* Instantiable */) {
return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType);
@@ -37878,7 +38193,7 @@ var ts;
if (flags & 393216 /* UnionOrIntersection */) {
return getTypeFactsOfTypes(type.types);
}
- return 8388607 /* All */;
+ return 4194303 /* All */;
}
function getTypeWithFacts(type, include) {
return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
@@ -38076,6 +38391,9 @@ var ts;
// is a union type, the mapping function is applied to each constituent type and a union
// of the resulting types is returned.
function mapType(type, mapper, noReductions) {
+ if (type.flags & 16384 /* Never */) {
+ return type;
+ }
if (!(type.flags & 131072 /* Union */)) {
return mapper(type);
}
@@ -38914,24 +39232,23 @@ var ts;
!(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */);
return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType;
}
- function isApparentTypePosition(node) {
+ function isConstraintPosition(node) {
var parent = node.parent;
return parent.kind === 183 /* PropertyAccessExpression */ ||
parent.kind === 185 /* CallExpression */ && parent.expression === node ||
parent.kind === 184 /* ElementAccessExpression */ && parent.expression === node ||
- parent.kind === 207 /* NonNullExpression */ ||
parent.kind === 180 /* BindingElement */ && parent.name === node && !!parent.initializer;
}
function typeHasNullableConstraint(type) {
return type.flags & 7372800 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */);
}
- function getApparentTypeForLocation(type, node) {
+ 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 (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) {
- return mapType(getWidenedType(type), getApparentType);
+ if (isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
+ return mapType(getWidenedType(type), getBaseConstraintOrType);
}
return type;
}
@@ -39008,7 +39325,7 @@ var ts;
checkCollisionWithCapturedThisVariable(node, node);
checkCollisionWithCapturedNewTargetVariable(node, node);
checkNestedBlockScopedBinding(node, symbol);
- var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node);
+ var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
var assignmentKind = ts.getAssignmentTargetKind(node);
if (assignmentKind) {
if (!(localOrExportSymbol.flags & 3 /* Variable */)) {
@@ -39658,7 +39975,7 @@ var ts;
var func = ts.getContainingFunction(node);
if (func) {
var functionFlags = ts.getFunctionFlags(func);
- if (functionFlags & 1 /* Generator */) {
+ if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
return undefined;
}
var contextualReturnType = getContextualReturnType(func);
@@ -39826,7 +40143,7 @@ var ts;
function getContextualTypeForChildJsxExpression(node) {
var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
// JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined;
}
function getContextualTypeForJsxExpression(node) {
@@ -39978,15 +40295,9 @@ var ts;
return anyType;
}
var isJs = ts.isInJavaScriptFile(node);
- return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes);
+ return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); });
}
- function getJsxSignaturesParameterTypes(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ false);
- }
- function getJsxSignaturesParameterTypesJs(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ true);
- }
- function getJsxSignaturesParameterTypesInternal(valueType, isJs) {
+ function getJsxSignaturesParameterTypes(valueType, isJs, context) {
// If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type
if (valueType.flags & 2 /* String */) {
return anyType;
@@ -39996,7 +40307,7 @@ var ts;
// For example:
// var CustomTag: "h1" = "h1";
// Hello World
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = valueType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -40022,21 +40333,21 @@ var ts;
return unknownType;
}
}
- return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0 /* None */);
+ return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */);
}
- function getJsxPropsTypeFromCallSignature(sig) {
+ function getJsxPropsTypeFromCallSignature(sig, context) {
var propsType = getTypeOfFirstParameterOfSignature(sig);
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
propsType = intersectTypes(intrinsicAttribs, propsType);
}
return propsType;
}
- function getJsxPropsTypeFromClassType(hostClassType, isJs) {
+ function getJsxPropsTypeFromClassType(hostClassType, isJs, context) {
if (isTypeAny(hostClassType)) {
return hostClassType;
}
- var propsName = getJsxElementPropertiesName();
+ var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context));
if (propsName === undefined) {
// There is no type ElementAttributesProperty, return 'any'
return anyType;
@@ -40058,14 +40369,14 @@ var ts;
else {
// Normal case -- add in IntrinsicClassElements and IntrinsicElements
var apparentAttributesType = attributesType;
- var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes);
+ var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
if (intrinsicClassAttribs !== unknownType) {
var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
apparentAttributesType = intersectTypes(typeParams
? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs))
: intrinsicClassAttribs, apparentAttributesType);
}
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
}
@@ -40073,18 +40384,12 @@ var ts;
}
}
}
- function getJsxPropsTypeFromConstructSignatureJs(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ true);
- }
- function getJsxPropsTypeFromConstructSignature(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ false);
- }
- function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) {
+ function getJsxPropsTypeFromConstructSignature(sig, isJs, context) {
var hostClassType = getReturnTypeOfSignature(sig);
if (hostClassType) {
- return getJsxPropsTypeFromClassType(hostClassType, isJs);
+ return getJsxPropsTypeFromClassType(hostClassType, isJs, context);
}
- return getJsxPropsTypeFromCallSignature(sig);
+ return getJsxPropsTypeFromCallSignature(sig, context);
}
// 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.
@@ -40374,9 +40679,13 @@ var ts;
}
typeFlags |= type.flags;
var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined;
- var prop = nameType && isTypeUsableAsLateBoundName(nameType)
+ var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType);
+ var prop = hasLateBoundName
? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */)
: createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName);
+ if (hasLateBoundName) {
+ prop.nameType = nameType;
+ }
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.
@@ -40500,7 +40809,7 @@ var ts;
}
function checkJsxSelfClosingElement(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode);
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxElement(node, checkMode) {
// Check attributes
@@ -40512,14 +40821,16 @@ var ts;
else {
checkExpression(node.closingElement.tagName);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxFragment(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode);
- if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) {
- error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory);
+ if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
+ error(node, compilerOptions.jsxFactory
+ ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
+ : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
/**
* Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
@@ -40564,7 +40875,7 @@ var ts;
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
var attributeDecl = _a[_i];
var member = attributeDecl.symbol;
@@ -40669,12 +40980,11 @@ var ts;
function checkJsxAttributes(node, checkMode) {
return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
}
- function getJsxType(name) {
- var jsxType = jsxTypes.get(name);
- if (jsxType === undefined) {
- jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType);
- }
- return jsxType;
+ function getJsxType(name, location) {
+ var namespace = getJsxNamespaceAt(location);
+ var exports = namespace && getExportsOfSymbol(namespace);
+ var typeSymbol = exports && getSymbol(exports, name, 793064 /* Type */);
+ return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType;
}
/**
* Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
@@ -40685,11 +40995,11 @@ var ts;
function getIntrinsicTagSymbol(node) {
var links = getNodeLinks(node);
if (!links.resolvedSymbol) {
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
if (intrinsicElementsType !== unknownType) {
// Property case
if (!ts.isIdentifier(node.tagName))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
if (intrinsicProp) {
links.jsxFlags |= 1 /* IntrinsicNamedElement */;
@@ -40742,7 +41052,7 @@ var ts;
var signature = signatures_3[_i];
if (signature.typeParameters) {
var isJavascript = ts.isInJavaScriptFile(node);
- var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */);
+ var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */);
var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext);
instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript));
}
@@ -40752,6 +41062,18 @@ var ts;
}
return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */);
}
+ function getJsxNamespaceAt(location) {
+ var namespaceName = getJsxNamespace(location);
+ var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
+ if (resolvedNamespace) {
+ var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */);
+ if (candidate) {
+ return candidate;
+ }
+ }
+ // JSX global fallback
+ return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined);
+ }
/**
* Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
* Get a single property from that container if existed. Report an error if there are more than one property.
@@ -40759,9 +41081,7 @@ var ts;
* @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
* if other string is given or the container doesn't exist, return undefined.
*/
- function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) {
- // JSX
- var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined);
+ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
// JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */);
// JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
@@ -40773,6 +41093,8 @@ var ts;
if (propertiesOfJsxElementAttribPropInterface.length === 0) {
return "";
}
+ // Element Attributes has one property, so the element attributes type will be the type of the corresponding
+ // property of the class instance type
else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
return propertiesOfJsxElementAttribPropInterface[0].escapedName;
}
@@ -40788,19 +41110,11 @@ var ts;
/// non-intrinsic elements' attributes type is 'any'),
/// or '' if it has 0 properties (which means every
/// non-intrinsic elements' attributes type is the element instance type)
- function getJsxElementPropertiesName() {
- if (!_hasComputedJsxElementPropertiesName) {
- _hasComputedJsxElementPropertiesName = true;
- _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer);
- }
- return _jsxElementPropertiesName;
+ function getJsxElementPropertiesName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
}
- function getJsxElementChildrenPropertyName() {
- if (!_hasComputedJsxElementChildrenPropertyName) {
- _hasComputedJsxElementChildrenPropertyName = true;
- _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer);
- }
- return _jsxElementChildrenPropertyName;
+ function getJsxElementChildrenPropertyName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
function getApparentTypeOfJsxPropsType(propsType) {
if (!propsType) {
@@ -40829,7 +41143,7 @@ var ts;
function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
ts.Debug.assert(!(elementType.flags & 131072 /* Union */));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
// We don't call getResolvedSignature here because we have already resolve the type of JSX Element.
var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined);
@@ -40839,7 +41153,7 @@ var ts;
paramType = getApparentTypeOfJsxPropsType(paramType);
if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
// Intersect in JSX.IntrinsicAttributes if it exists
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
paramType = intersectTypes(intrinsicAttributes, paramType);
}
@@ -40864,7 +41178,7 @@ var ts;
ts.Debug.assert(!(elementType.flags & 131072 /* Union */));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
// Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
// We don't call getResolvedSignature because here we have already resolve the type of JSX Element.
var candidatesOutArray = [];
@@ -40898,7 +41212,7 @@ var ts;
result = allMatchingAttributesType;
}
// Intersect in JSX.IntrinsicAttributes if it exists
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
result = intersectTypes(intrinsicAttributes, result);
}
@@ -40941,7 +41255,7 @@ var ts;
// For example:
// var CustomTag: "h1" = "h1";
// Hello World
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = elementType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -40971,7 +41285,7 @@ var ts;
if (elementClassType) {
checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
}
- return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement));
+ return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement);
}
/**
* Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
@@ -41002,7 +41316,7 @@ var ts;
* @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component
*/
function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) {
- return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType());
+ return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node));
}
/**
* Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element.
@@ -41042,32 +41356,26 @@ var ts;
var prop = getPropertyOfType(attributesType, attrib.name.escapedText);
return prop || unknownSymbol;
}
- function getJsxGlobalElementClassType() {
- if (!deferredJsxElementClassType) {
- deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass);
- }
- return deferredJsxElementClassType;
+ function getJsxElementClassTypeAt(location) {
+ var type = getJsxType(JsxNames.ElementClass, location);
+ if (type === unknownType)
+ return undefined;
+ return type;
}
- function getJsxGlobalElementType() {
- if (!deferredJsxElementType) {
- deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element);
- }
- return deferredJsxElementType;
+ function getJsxElementTypeAt(location) {
+ return getJsxType(JsxNames.Element, location);
}
- function getJsxGlobalStatelessElementType() {
- if (!deferredJsxStatelessElementType) {
- var jsxElementType = getJsxGlobalElementType();
- if (jsxElementType) {
- deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]);
- }
+ function getJsxStatelessElementTypeAt(location) {
+ var jsxElementType = getJsxElementTypeAt(location);
+ if (jsxElementType) {
+ return getUnionType([jsxElementType, nullType]);
}
- return deferredJsxStatelessElementType;
}
/**
* Returns all the properties of the Jsx.IntrinsicElements interface
*/
- function getJsxIntrinsicTagNames() {
- var intrinsics = getJsxType(JsxNames.IntrinsicElements);
+ function getJsxIntrinsicTagNamesAt(location) {
+ var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
}
function checkJsxPreconditions(errorNode) {
@@ -41075,7 +41383,7 @@ var ts;
if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
}
- if (getJsxGlobalElementType() === undefined) {
+ if (getJsxElementTypeAt(errorNode) === undefined) {
if (noImplicitAny) {
error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
}
@@ -41090,7 +41398,7 @@ var ts;
// The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
// And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
- var reactNamespace = getJsxNamespace();
+ var reactNamespace = getJsxNamespace(node);
var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
var reactSym = resolveName(reactLocation, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
if (reactSym) {
@@ -41166,7 +41474,7 @@ var ts;
// If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type.
// but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass.
if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || getPropertiesOfType(sourceAttributesType).length > 0)) {
- error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName()));
+ error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement))));
}
else {
// Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties
@@ -41373,7 +41681,7 @@ var ts;
return unknownType;
}
}
- propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node);
+ propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
}
// 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,
@@ -41499,6 +41807,10 @@ var ts;
});
return result && ts.symbolName(result);
}
+ function getSuggestionForNonexistentModule(name, targetModule) {
+ var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
+ return suggestion && ts.symbolName(suggestion);
+ }
/**
* Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
* Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
@@ -41911,13 +42223,13 @@ var ts;
}
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
- var context = createInferenceContext(signature, 1 /* InferUnionTypes */, compareTypes);
+ var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes);
forEachMatchingParameterType(contextualSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target);
});
if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */);
+ inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration));
}
@@ -41968,7 +42280,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, 4 /* ReturnType */);
+ inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -42601,7 +42913,7 @@ var ts;
}
var candidate = void 0;
var inferenceContext = originalCandidate.typeParameters ?
- createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) :
+ createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) :
undefined;
while (true) {
candidate = originalCandidate;
@@ -43173,7 +43485,7 @@ var ts;
}
// Make sure require is not a local function
if (!ts.isIdentifier(node.expression))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
if (!resolvedRequire) {
// project does not contain symbol named 'require' - assume commonjs require
@@ -43365,7 +43677,7 @@ var ts;
}
else {
var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
- if (functionFlags & 1 /* Generator */) {
+ if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types);
if (!types || types.length === 0) {
var iterableIteratorAny = functionFlags & 2 /* Async */
@@ -43631,7 +43943,7 @@ var ts;
((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ?
checkAsyncFunctionReturnType(node) : // Async function
getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function
- if ((functionFlags & 1 /* Generator */) === 0) {
+ if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
// return is not necessary in the body of generators
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
}
@@ -43655,11 +43967,11 @@ var ts;
// its return type annotation.
var exprType = checkExpression(node.body);
if (returnOrPromisedType) {
- if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) {
+ if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body);
}
- else {
+ else { // Normal function
checkTypeAssignableTo(exprType, returnOrPromisedType, node.body);
}
}
@@ -44816,6 +45128,7 @@ var ts;
if (node.kind === 159 /* 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 === 162 /* FunctionType */ || node.kind === 232 /* FunctionDeclaration */ || node.kind === 163 /* ConstructorType */ ||
node.kind === 157 /* CallSignature */ || node.kind === 154 /* Constructor */ ||
node.kind === 158 /* ConstructSignature */) {
@@ -45634,7 +45947,7 @@ var ts;
case 230 /* VariableDeclaration */:
case 180 /* BindingElement */:
case 232 /* FunctionDeclaration */:
- case 246 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591
+ case 246 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
return 1 /* ExportValue */;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(d));
@@ -46158,7 +46471,7 @@ var ts;
var body = node.kind === 152 /* MethodSignature */ ? undefined : node.body;
checkSourceElement(body);
var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
- if ((functionFlags & 1 /* Generator */) === 0) {
+ if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */
? checkAsyncFunctionReturnType(node) // Async function
: getTypeFromTypeNode(returnTypeNode)); // normal function
@@ -46533,7 +46846,7 @@ var ts;
var symbol = getSymbolOfNode(node);
if (symbol.flags & 1 /* FunctionScopedVariable */) {
if (!ts.isIdentifier(node.name))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
if (localDeclarationSymbol &&
localDeclarationSymbol !== symbol &&
@@ -47236,7 +47549,7 @@ var ts;
var isGenerator = functionFlags & 1 /* Generator */;
if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) {
var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
- if (isGenerator) {
+ if (isGenerator) { // AsyncGenerator function or Generator function
// A generator does not need its return expressions checked against its return type.
// Instead, the yield expressions are checked against the element type.
// TODO: Check return types of generators when return type tracking is added
@@ -47254,7 +47567,7 @@ var ts;
}
}
else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) {
- if (functionFlags & 2 /* Async */) {
+ if (functionFlags & 2 /* Async */) { // Async function
var promisedType = getPromisedTypeOfPromise(returnType);
var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
if (promisedType) {
@@ -47696,7 +48009,7 @@ var ts;
var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
if (prop && baseProp) {
var rootChain = function () { return ts.chainDiagnosticMessages(
- /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); };
+ /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); };
if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
issuedMemberError = true;
}
@@ -48211,7 +48524,6 @@ var ts;
// - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
if (checkBody && node.body) {
- // body of ambient external module is always a module block
for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
var statement = _a[_i];
checkModuleAugmentationElement(statement, isGlobalAugmentation);
@@ -48316,7 +48628,11 @@ var ts;
}
function checkExternalImportOrExportDeclaration(node) {
var moduleName = ts.getExternalModuleName(node);
- if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) {
+ if (ts.nodeIsMissing(moduleName)) {
+ // Should be a parse error.
+ return false;
+ }
+ if (!ts.isStringLiteral(moduleName)) {
error(moduleName, ts.Diagnostics.String_literal_expected);
return false;
}
@@ -48327,7 +48643,7 @@ var ts;
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
return false;
}
- if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) {
+ if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
// we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration
// no need to do this again.
if (!isTopLevelInExternalModuleAugmentation(node)) {
@@ -49915,7 +50231,7 @@ var ts;
return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */);
},
writeLiteralConstValue: writeLiteralConstValue,
- getJsxFactoryEntity: function () { return _jsxFactoryEntity; }
+ getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }
};
// defined here to avoid outer scope pollution
function getTypeReferenceDirectivesForEntityName(node) {
@@ -51328,7 +51644,7 @@ var ts;
case 243 /* ImportClause */: // For default import
case 241 /* ImportEqualsDeclaration */:
case 244 /* NamespaceImport */:
- case 246 /* ImportSpecifier */:// For rename import `x as y`
+ case 246 /* ImportSpecifier */: // For rename import `x as y`
return true;
case 71 /* Identifier */:
// For regular import, `decl` is an Identifier under the ImportSpecifier.
@@ -51546,9 +51862,15 @@ var ts;
: node;
}
ts.updateQualifiedName = updateQualifiedName;
+ function parenthesizeForComputedName(expression) {
+ return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) ||
+ expression.kind === 296 /* CommaListExpression */ ?
+ createParen(expression) :
+ expression;
+ }
function createComputedPropertyName(expression) {
var node = createSynthesizedNode(146 /* ComputedPropertyName */);
- node.expression = expression;
+ node.expression = parenthesizeForComputedName(expression);
return node;
}
ts.createComputedPropertyName = createComputedPropertyName;
@@ -53345,7 +53667,7 @@ var ts;
var node = createSynthesizedNode(268 /* PropertyAssignment */);
node.name = asName(name);
node.questionToken = undefined;
- node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
+ node.initializer = ts.parenthesizeExpressionForList(initializer);
return node;
}
ts.createPropertyAssignment = createPropertyAssignment;
@@ -53455,6 +53777,12 @@ var ts;
updated.imports = node.imports;
if (node.moduleAugmentations !== undefined)
updated.moduleAugmentations = node.moduleAugmentations;
+ if (node.pragmas !== undefined)
+ updated.pragmas = node.pragmas;
+ if (node.localJsxFactory !== undefined)
+ updated.localJsxFactory = node.localJsxFactory;
+ if (node.localJsxNamespace !== undefined)
+ updated.localJsxNamespace = node.localJsxNamespace;
return updateNode(updated, node);
}
return node;
@@ -56384,7 +56712,7 @@ var ts;
var isDebugInfoEnabled = false;
Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */)
? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); }
- : ts.noop;
+ : ts.noop; // TODO: GH#22091
Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */)
? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); }
: ts.noop;
@@ -56489,7 +56817,7 @@ var ts;
var uniqueExports = ts.createMap();
var exportedNames;
var hasExportDefault = false;
- var exportEquals = undefined;
+ var exportEquals;
var hasExportStarsToExportValues = false;
var hasImportStarOrImportDefault = false;
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
@@ -58093,7 +58421,7 @@ var ts;
ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
var localName = ts.getMutableClone(name);
ts.setEmitFlags(localName, 1536 /* NoComments */);
- return ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)));
+ return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */));
}
/**
* Gets all property declarations with initializers on either the static or instance side of a class.
@@ -58756,6 +59084,8 @@ var ts;
// One of the individual is global object, return immediately
return serializedIndividual;
}
+ // If there exists union that is not void 0 expression, check if the the common type is identifier.
+ // anything more complex and we will just default to Object
else if (serializedUnion) {
// Different types
if (!ts.isIdentifier(serializedUnion) ||
@@ -58919,7 +59249,7 @@ var ts;
function visitPropertyNameOfClassElement(member) {
var name = member.name;
var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false);
- if (expr) {
+ if (expr) { // expr only exists if `name` is a computed property name
// Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order
if (ts.some(pendingExpressions)) {
expr = ts.inlineExpressions(pendingExpressions.concat([expr]));
@@ -61270,14 +61600,14 @@ var ts;
objectProperties = ts.createAssignHelper(context, segments);
}
}
- var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
return element;
}
function visitJsxOpeningFragment(node, children, isChild, location) {
- var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
@@ -62469,6 +62799,7 @@ var ts;
if (statement.kind === 223 /* ReturnStatement */) {
return true;
}
+ // An if-statement with two covered branches is covered.
else if (statement.kind === 215 /* IfStatement */) {
var ifStatement = statement;
if (ifStatement.elseStatement) {
@@ -62476,6 +62807,7 @@ var ts;
isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
}
}
+ // A block is covered if it has a last statement which is covered.
else if (statement.kind === 211 /* Block */) {
var lastStatement = ts.lastOrUndefined(statement.statements);
if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
@@ -62674,11 +63006,11 @@ var ts;
function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
initializer = ts.visitNode(initializer, visitor, ts.isExpression);
var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
- ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter))
- ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */));
+ ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
+ ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
- ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */);
+ ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
statements.push(statement);
}
/**
@@ -67155,6 +67487,7 @@ var ts;
withBlockStack.pop();
}
break;
+ // default: do nothing
}
}
}
@@ -68801,13 +69134,13 @@ var ts;
var importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
- text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}"
+ text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
var importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
- text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}"
+ text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
};
})(ts || (ts = {}));
///
@@ -70918,8 +71251,8 @@ var ts;
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = ts.createMap();
}
- for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) {
- var directive = typeReferenceDirectives_1[_i];
+ for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
+ var directive = typeReferenceDirectives_2[_i];
if (!usedTypeDirectiveReferences.has(directive)) {
usedTypeDirectiveReferences.set(directive, directive);
}
@@ -71208,7 +71541,12 @@ var ts;
"?");
}
write(": ");
- emitType(node.type);
+ if (node.type) {
+ emitType(node.type);
+ }
+ else {
+ write("any");
+ }
write(";");
writeLine();
decreaseIndent();
@@ -71299,6 +71637,7 @@ var ts;
if (isModuleElementVisible) {
writeModuleElement(node);
}
+ // Import equals declaration in internal module can become visible as part of any emit so lets make sure we add these irrespective
else if (node.kind === 241 /* ImportEqualsDeclaration */ ||
(node.parent.kind === 272 /* SourceFile */ && isCurrentFileExternalModule)) {
var isVisible = void 0;
@@ -71852,6 +72191,8 @@ var ts;
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;
}
+ // 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 === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ ||
(node.kind === 148 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
@@ -72604,7 +72945,7 @@ var ts;
}
if (compilerOptions.mapRoot) {
sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot);
- if (sourceFileOrBundle.kind === 272 /* SourceFile */) {
+ if (sourceFileOrBundle.kind === 272 /* SourceFile */) { // emitting single module file
// For modules or multiple emit files the mapRoot will have directory structure like the sources
// So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir));
@@ -73930,6 +74271,8 @@ var ts;
// Enum
case 271 /* EnumMember */:
return emitEnumMember(node);
+ // JSDoc nodes (ignored)
+ // Transformation nodes (ignored)
}
// If the node is an expression, try to emit it as an expression with
// substitution.
@@ -74125,7 +74468,8 @@ var ts;
else {
emitTypeAnnotation(node.type);
}
- emitInitializer(node.initializer);
+ // 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);
}
function emitDecorator(decorator) {
writePunctuation("@");
@@ -74147,8 +74491,9 @@ var ts;
emitModifiers(node, node.modifiers);
emit(node.name);
emitIfPresent(node.questionToken);
+ emitIfPresent(node.exclamationToken);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
writeSemicolon();
}
function emitMethodSignature(node) {
@@ -74393,7 +74738,7 @@ var ts;
writeSpace();
}
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
//
// Expressions
@@ -74430,7 +74775,10 @@ var ts;
emitExpression(node.expression);
increaseIndentIf(indentBeforeDot);
var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression);
- writePunctuation(shouldEmitDotDot ? ".." : ".");
+ if (shouldEmitDotDot) {
+ writePunctuation(".");
+ }
+ emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node);
increaseIndentIf(indentAfterDot);
emit(node.name);
decreaseIndentIf(indentBeforeDot, indentAfterDot);
@@ -74456,9 +74804,9 @@ var ts;
}
function emitElementAccessExpression(node) {
emitExpression(node.expression);
- writePunctuation("[");
+ var openPos = emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
emitExpression(node.argumentExpression);
- writePunctuation("]");
+ emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node);
}
function emitCallExpression(node) {
emitExpression(node.expression);
@@ -74466,7 +74814,7 @@ var ts;
emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */);
}
function emitNewExpression(node) {
- writeKeyword("new");
+ emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
emitTypeArguments(node, node.typeArguments);
@@ -74484,9 +74832,9 @@ var ts;
emitExpression(node.expression);
}
function emitParenthesizedExpression(node) {
- writePunctuation("(");
+ var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
}
function emitFunctionExpression(node) {
emitFunctionDeclarationOrExpression(node);
@@ -74504,22 +74852,22 @@ var ts;
emit(node.equalsGreaterThanToken);
}
function emitDeleteExpression(node) {
- writeKeyword("delete");
+ emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitTypeOfExpression(node) {
- writeKeyword("typeof");
+ emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitVoidExpression(node) {
- writeKeyword("void");
+ emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitAwaitExpression(node) {
- writeKeyword("await");
+ emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
@@ -74587,7 +74935,7 @@ var ts;
emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */);
}
function emitYieldExpression(node) {
- writeKeyword("yield");
+ emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node);
emit(node.asteriskToken);
emitExpressionWithLeadingSpace(node.expression);
}
@@ -74631,17 +74979,13 @@ var ts;
// Statements
//
function emitBlock(node) {
- writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
- // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted
- increaseIndent();
- emitLeadingCommentsOfPosition(node.statements.end);
- decreaseIndent();
- writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node);
}
function emitBlockStatements(node, forceSingleLine) {
+ emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */;
emitList(node, node.statements, format);
+ emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
}
function emitVariableStatement(node) {
emitModifiers(node, node.modifiers);
@@ -74656,15 +75000,15 @@ var ts;
writeSemicolon();
}
function emitIfStatement(node) {
- var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node);
+ var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.thenStatement);
if (node.elseStatement) {
writeLineOrSpace(node);
- writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
+ emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
if (node.elseStatement.kind === 215 /* IfStatement */) {
writeSpace();
emit(node.elseStatement);
@@ -74674,8 +75018,15 @@ var ts;
}
}
}
+ function emitWhileClause(node, startPos) {
+ var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node);
+ writeSpace();
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
+ emitExpression(node.expression);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
+ }
function emitDoStatement(node) {
- writeKeyword("do");
+ emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node);
emitEmbeddedStatement(node, node.statement);
if (ts.isBlock(node.statement)) {
writeSpace();
@@ -74683,55 +75034,48 @@ var ts;
else {
writeLineOrSpace(node);
}
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(");");
+ emitWhileClause(node, node.statement.end);
+ writePunctuation(";");
}
function emitWhileStatement(node) {
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(")");
+ emitWhileClause(node, node.pos);
emitEmbeddedStatement(node, node.statement);
}
function emitForStatement(node) {
- var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
+ var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
emitForBinding(node.initializer);
- writeSemicolon();
+ pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.condition);
- writeSemicolon();
+ pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.incrementor);
- writePunctuation(")");
+ emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForInStatement(node) {
- var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("in");
+ emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForOfStatement(node) {
- var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitWithTrailingSpace(node.awaitModifier);
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("of");
+ emitTokenWithComment(144 /* OfKeyword */, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForBinding(node) {
@@ -74745,22 +75089,34 @@ var ts;
}
}
function emitContinueStatement(node) {
- writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword);
+ emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
function emitBreakStatement(node) {
- writeToken(72 /* BreakKeyword */, node.pos, writeKeyword);
+ emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
- function emitTokenWithComment(token, pos, writer, contextNode) {
+ function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
var node = contextNode && ts.getParseTreeNode(contextNode);
- if (node && node.kind === contextNode.kind) {
+ var isSimilarNode = node && node.kind === contextNode.kind;
+ var startPos = pos;
+ if (isSimilarNode) {
pos = ts.skipTrivia(currentSourceFile.text, pos);
}
- pos = writeToken(token, pos, writer, /*contextNode*/ contextNode);
- if (node && node.kind === contextNode.kind) {
+ if (emitLeadingCommentsOfPosition && isSimilarNode) {
+ var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
+ if (needsIndent) {
+ increaseIndent();
+ }
+ emitLeadingCommentsOfPosition(startPos);
+ if (needsIndent) {
+ decreaseIndent();
+ }
+ }
+ pos = writeTokenText(token, writer, pos);
+ if (emitTrailingCommentsOfPosition && isSimilarNode) {
emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
}
return pos;
@@ -74771,35 +75127,35 @@ var ts;
writeSemicolon();
}
function emitWithStatement(node) {
- writeKeyword("with");
+ var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writePunctuation("(");
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitSwitchStatement(node) {
- var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
writeSpace();
emit(node.caseBlock);
}
function emitLabeledStatement(node) {
emit(node.label);
- writePunctuation(":");
+ emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node);
writeSpace();
emit(node.statement);
}
function emitThrowStatement(node) {
- writeKeyword("throw");
+ emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node);
emitExpressionWithLeadingSpace(node.expression);
writeSemicolon();
}
function emitTryStatement(node) {
- writeKeyword("try");
+ emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node);
writeSpace();
emit(node.tryBlock);
if (node.catchClause) {
@@ -74808,7 +75164,7 @@ var ts;
}
if (node.finallyBlock) {
writeLineOrSpace(node);
- writeKeyword("finally");
+ emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
writeSpace();
emit(node.finallyBlock);
}
@@ -74823,7 +75179,7 @@ var ts;
function emitVariableDeclaration(node) {
emit(node.name);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
}
function emitVariableDeclarationList(node) {
writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var");
@@ -75024,23 +75380,21 @@ var ts;
}
function emitModuleBlock(node) {
pushNameGenerationScope(node);
- writePunctuation("{");
emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
- writePunctuation("}");
popNameGenerationScope(node);
}
function emitCaseBlock(node) {
- writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation);
+ emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node);
emitList(node, node.clauses, 65 /* CaseBlockClauses */);
- writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation);
+ emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
}
function emitImportEqualsDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSpace();
- writePunctuation("=");
+ emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node);
writeSpace();
emitModuleReference(node.moduleReference);
writeSemicolon();
@@ -75055,12 +75409,12 @@ var ts;
}
function emitImportDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
if (node.importClause) {
emit(node.importClause);
writeSpace();
- writeKeyword("from");
+ emitTokenWithComment(142 /* FromKeyword */, node.importClause.end, writeKeyword, node);
writeSpace();
}
emitExpression(node.moduleSpecifier);
@@ -75069,15 +75423,15 @@ var ts;
function emitImportClause(node) {
emit(node.name);
if (node.name && node.namedBindings) {
- writePunctuation(",");
+ emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node);
writeSpace();
}
emit(node.namedBindings);
}
function emitNamespaceImport(node) {
- writePunctuation("*");
+ var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node);
writeSpace();
emit(node.name);
}
@@ -75088,41 +75442,42 @@ var ts;
emitImportOrExportSpecifier(node);
}
function emitExportAssignment(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
writeSpace();
if (node.isExportEquals) {
- writeOperator("=");
+ emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node);
}
else {
- writeKeyword("default");
+ emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node);
}
writeSpace();
emitExpression(node.expression);
writeSemicolon();
}
function emitExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
writeSpace();
if (node.exportClause) {
emit(node.exportClause);
}
else {
- writePunctuation("*");
+ nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node);
}
if (node.moduleSpecifier) {
writeSpace();
- writeKeyword("from");
+ var fromPos = node.exportClause ? node.exportClause.end : nextPos;
+ emitTokenWithComment(142 /* FromKeyword */, fromPos, writeKeyword, node);
writeSpace();
emitExpression(node.moduleSpecifier);
}
writeSemicolon();
}
function emitNamespaceExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeKeyword("as");
+ nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node);
writeSpace();
- writeKeyword("namespace");
+ nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSemicolon();
@@ -75142,7 +75497,7 @@ var ts;
if (node.propertyName) {
emit(node.propertyName);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
writeSpace();
}
emit(node.name);
@@ -75234,44 +75589,31 @@ var ts;
// Clauses
//
function emitCaseClause(node) {
- writeKeyword("case");
+ emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
}
function emitDefaultClause(node) {
- writeKeyword("default");
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node);
+ emitCaseOrDefaultClauseRest(node, node.statements, pos);
}
- function emitCaseOrDefaultClauseStatements(parentNode, statements) {
+ function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
var emitAsSingleStatement = statements.length === 1 &&
(
// treat synthesized nodes as located on the same line for emit purposes
ts.nodeIsSynthesized(parentNode) ||
ts.nodeIsSynthesized(statements[0]) ||
ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
- // e.g:
- // case 0: // Zero
- // case 1: // One
- // case 2: // two
- // return "hi";
- // If there is no statements, emitNodeWithComments of the parentNode which is caseClause will take care of trailing comment.
- // So in example above, comment "// Zero" and "// One" will be emit in emitTrailingComments in emitNodeWithComments.
- // However, for "case 2", because parentNode which is caseClause has an "end" property to be end of the statements (in this case return statement)
- // comment "// two" will not be emitted in emitNodeWithComments.
- // Therefore, we have to do the check here to emit such comment.
- if (statements.length > 0) {
- // We use emitTrailingCommentsOfPosition instead of emitLeadingCommentsOfPosition because leading comments is defined as comments before the node after newline character separating it from previous line
- // Note: we can't use parentNode.end as such position includes statements.
- emitTrailingCommentsOfPosition(statements.pos);
- }
var format = 81985 /* CaseOrDefaultClauseStatements */;
if (emitAsSingleStatement) {
+ writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode);
writeSpace();
format &= ~(1 /* MultiLine */ | 64 /* Indented */);
}
+ else {
+ emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode);
+ }
emitList(parentNode, statements, format);
}
function emitHeritageClause(node) {
@@ -75281,12 +75623,12 @@ var ts;
emitList(node, node.types, 272 /* HeritageClauseTypes */);
}
function emitCatchClause(node) {
- var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node);
writeSpace();
if (node.variableDeclaration) {
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emit(node.variableDeclaration);
- writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
writeSpace();
}
emit(node.block);
@@ -75332,7 +75674,7 @@ var ts;
//
function emitEnumMember(node) {
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
//
// Top-level nodes
@@ -75449,10 +75791,10 @@ var ts;
emit(node);
}
}
- function emitInitializer(node) {
+ function emitInitializer(node, equalCommentStartPos, container) {
if (node) {
writeSpace();
- writeOperator("=");
+ emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
writeSpace();
emitExpression(node);
}
@@ -75500,7 +75842,7 @@ var ts;
emitList(parentNode, typeArguments, 26896 /* TypeArguments */);
}
function emitTypeParameters(parentNode, typeParameters) {
- if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) {
+ if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
return emitTypeArguments(parentNode, parentNode.typeArguments);
}
emitList(parentNode, typeParameters, 26896 /* TypeParameters */);
@@ -75577,6 +75919,9 @@ var ts;
}
if (format & 7680 /* BracketsMask */) {
writePunctuation(getOpeningBracket(format));
+ if (isEmpty) {
+ emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
+ }
}
if (onBeforeEmitNodeArray) {
onBeforeEmitNodeArray(children);
@@ -75684,6 +76029,9 @@ var ts;
onAfterEmitNodeArray(children);
}
if (format & 7680 /* BracketsMask */) {
+ if (isEmpty) {
+ emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
+ }
writePunctuation(getClosingBracket(format));
}
}
@@ -76264,7 +76612,7 @@ var ts;
if (failed) {
return "";
}
- if (!commonPathComponents) {
+ if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
@@ -76396,8 +76744,7 @@ var ts;
}
ts.formatDiagnostics = formatDiagnostics;
function formatDiagnostic(diagnostic, host) {
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
+ var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
@@ -76422,8 +76769,9 @@ var ts;
var ellipsis = "...";
function getCategoryFormat(category) {
switch (category) {
- case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
+ case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
+ case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
}
}
@@ -76454,8 +76802,8 @@ var ts;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
- context += host.getNewLine();
for (var i = firstLine; i <= lastLine; i++) {
+ context += host.getNewLine();
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
@@ -76496,9 +76844,7 @@ var ts;
output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
output += " - ";
}
- var categoryColor = getCategoryFormat(diagnostic.category);
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- output += formatColorAndReset(category, categoryColor);
+ output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file) {
@@ -77651,6 +77997,7 @@ var ts;
if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
(imports || (imports = [])).push(node.arguments[0]);
}
+ // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) {
(imports || (imports = [])).push(node.arguments[0]);
}
@@ -77751,6 +78098,7 @@ var ts;
modulesWithElidedImports.set(file_1.path, false);
processImportedModules(file_1);
}
+ // See if we need to reprocess the imports due to prior skipped imports
else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
modulesWithElidedImports.set(file_1.path, false);
@@ -78089,7 +78437,7 @@ var ts;
// 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.sourceRoot || // there is --sourceRoot specified
- options.mapRoot) {
+ options.mapRoot) { // there is --mapRoot specified
// Precalculate and cache the common source directory
var dir = getCommonSourceDirectory();
// If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
@@ -78316,7 +78664,6 @@ var ts;
if (aug.kind === 9 /* StringLiteral */) {
res.push(aug.text);
}
- // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
}
return res;
}
@@ -78741,16 +79088,13 @@ var ts;
}
ts.getTargetLabel = getTargetLabel;
function isJumpStatementTarget(node) {
- return node.kind === 71 /* Identifier */ &&
- (node.parent.kind === 222 /* BreakStatement */ || node.parent.kind === 221 /* ContinueStatement */) &&
- node.parent.label === node;
+ return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node;
}
ts.isJumpStatementTarget = isJumpStatementTarget;
function isLabelOfLabeledStatement(node) {
- return node.kind === 71 /* Identifier */ &&
- node.parent.kind === 226 /* LabeledStatement */ &&
- node.parent.label === node;
+ return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node;
}
+ ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement;
function isLabelName(node) {
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
@@ -79116,12 +79460,7 @@ var ts;
// be parented by the container of the SyntaxList, not the SyntaxList itself.
// In order to find the list item index, we first need to locate SyntaxList itself and then search
// for the position of the relevant node (or comma).
- var syntaxList = ts.forEach(node.parent.getChildren(), function (c) {
- // find syntax list that covers the span of the node
- if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) {
- return c;
- }
- });
+ var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); });
// Either we didn't find an appropriate list, or the list must contain us.
ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node));
return syntaxList;
@@ -79876,7 +80215,7 @@ var ts;
}
function suppressTrailing(node) {
ts.addEmitFlags(node, 1024 /* NoTrailingComments */);
- var lastChild = undefined;
+ var lastChild;
ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) {
// As an optimization, jump straight to the end of the list.
if (children.length) {
@@ -80111,24 +80450,23 @@ var ts;
return textSpan(node);
}
if (node.kind === 198 /* BinaryExpression */) {
- var binaryExpression = node;
+ 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
// [a, b, c] = expression or
// {a, b, c} = expression
- if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) {
- return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left);
+ if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
+ return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left);
}
- if (binaryExpression.operatorToken.kind === 58 /* EqualsToken */ &&
- ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) {
+ if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
// Set breakpoint on assignment expression element of destructuring pattern
// a = expression of
// [a = expression, b, c] = someExpression or
// { a = expression, b, c } = someExpression
return textSpan(node);
}
- if (binaryExpression.operatorToken.kind === 26 /* CommaToken */) {
- return spanInNode(binaryExpression.left);
+ if (operatorToken.kind === 26 /* CommaToken */) {
+ return spanInNode(left);
}
}
if (ts.isExpressionNode(node)) {
@@ -80156,46 +80494,49 @@ var ts;
break;
}
}
- // If this is name of property assignment, set breakpoint in the initializer
- if (node.parent.kind === 268 /* PropertyAssignment */ &&
- node.parent.name === node &&
- !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
- return spanInNode(node.parent.initializer);
- }
- // Breakpoint in type assertion goes to its operand
- if (node.parent.kind === 188 /* TypeAssertionExpression */ && node.parent.type === node) {
- return spanInNextNode(node.parent.type);
- }
- // return type of function go to previous token
- if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
- return spanInPreviousNode(node);
- }
- // initializer of variable/parameter declaration go to previous node
- if ((node.parent.kind === 230 /* VariableDeclaration */ ||
- node.parent.kind === 148 /* Parameter */)) {
- var paramOrVarDecl = node.parent;
- if (paramOrVarDecl.initializer === node ||
- paramOrVarDecl.type === node ||
- ts.isAssignmentOperator(node.kind)) {
- return spanInPreviousNode(node);
+ switch (node.parent.kind) {
+ case 268 /* 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 188 /* TypeAssertionExpression */:
+ // Breakpoint in type assertion goes to its operand
+ if (node.parent.type === node) {
+ return spanInNextNode(node.parent.type);
+ }
+ break;
+ case 230 /* VariableDeclaration */:
+ case 148 /* 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)) {
+ return spanInPreviousNode(node);
+ }
+ break;
}
- }
- if (node.parent.kind === 198 /* BinaryExpression */) {
- var binaryExpression = node.parent;
- if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) &&
- (binaryExpression.right === node ||
- binaryExpression.operatorToken === node)) {
- // If initializer of destructuring assignment move to previous token
- return spanInPreviousNode(node);
+ case 198 /* BinaryExpression */: {
+ var left = node.parent.left;
+ if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
+ // If initializer of destructuring assignment move to previous token
+ return spanInPreviousNode(node);
+ }
+ break;
}
+ default:
+ // return type of function go to previous token
+ if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
+ return spanInPreviousNode(node);
+ }
}
// Default go to parent to set the breakpoint
return spanInNode(node.parent);
}
}
function textSpanFromVariableDeclaration(variableDeclaration) {
- if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ &&
- variableDeclaration.parent.declarations[0] === variableDeclaration) {
+ if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
// First declaration - include let keyword
return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
}
@@ -80220,7 +80561,7 @@ var ts;
variableDeclaration.parent.parent.kind === 220 /* ForOfStatement */) {
return textSpanFromVariableDeclaration(variableDeclaration);
}
- if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ &&
+ if (ts.isVariableDeclarationList(variableDeclaration.parent) &&
variableDeclaration.parent.declarations[0] !== variableDeclaration) {
// If we cannot set breakpoint on this declaration, set it on previous one
// Because the variable declaration may be binding pattern and
@@ -80706,7 +81047,7 @@ var ts;
case 13 /* NoSubstitutionTemplateLiteral */:
return 4 /* InTemplateHeadOrNoSubstitutionTemplate */;
default:
- throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
+ return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
}
}
return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined;
@@ -80813,7 +81154,7 @@ var ts;
case 0 /* None */:
return { prefix: "" };
default:
- throw ts.Debug.assertNever(lexState);
+ return ts.Debug.assertNever(lexState);
}
}
function isBinaryExpressionOperatorToken(token) {
@@ -81660,7 +82001,7 @@ var ts;
try {
typeRoots = ts.getEffectiveTypeRoots(options, host);
}
- catch (_b) { }
+ catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ }
if (typeRoots) {
for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) {
var root = typeRoots_2[_c];
@@ -81808,7 +82149,7 @@ var ts;
try {
return ts.directoryProbablyExists(path, host);
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return undefined;
}
function tryIOAndConsumeErrors(host, toApply) {
@@ -81819,7 +82160,7 @@ var ts;
try {
return toApply && toApply.apply(host, args);
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return undefined;
}
})(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {}));
@@ -81870,7 +82211,7 @@ var ts;
case 3 /* JsDocParameterName */:
return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag));
default:
- throw ts.Debug.assertNever(completionData);
+ return ts.Debug.assertNever(completionData);
}
}
Completions.getCompletionsAtPosition = getCompletionsAtPosition;
@@ -81907,7 +82248,7 @@ var ts;
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
}
function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) {
- var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
+ var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
if (sourceFile.languageVariant === 1 /* JSX */ && 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.
@@ -81942,7 +82283,7 @@ var ts;
if (keywordFilters !== 0 /* None */ || !isMemberCompletion) {
ts.addRange(entries, getKeywordCompletions(keywordFilters));
}
- return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
+ return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
}
function isMemberCompletionKind(kind) {
switch (kind) {
@@ -82291,7 +82632,6 @@ var ts;
var CompletionKind;
(function (CompletionKind) {
CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration";
- /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */
CompletionKind[CompletionKind["Global"] = 1] = "Global";
CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess";
CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike";
@@ -82378,6 +82718,7 @@ var ts;
var insideComment = ts.isInComment(sourceFile, position, currentToken);
log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
var insideJsDocTagTypeExpression = false;
+ var isInSnippetScope = false;
if (insideComment) {
if (ts.hasDocComment(sourceFile, position)) {
if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
@@ -82551,7 +82892,7 @@ var ts;
getTypeScriptMemberSymbols();
}
else if (isRightOfOpenTag) {
- var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNames(), "getJsxIntrinsicTagNames() should all be defined");
+ var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
if (tryGetGlobalSymbols()) {
symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 2097152 /* Alias */)); }));
}
@@ -82578,7 +82919,7 @@ var ts;
}
log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart));
var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, position, sourceFile, typeChecker);
- return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
+ return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
case 287 /* JSDocParameterTag */:
@@ -82688,7 +83029,7 @@ var ts;
keywordFilters = 3 /* FunctionLikeBodyKeywords */;
}
// Get all entities in the current scope.
- completionKind = 5 /* None */;
+ completionKind = 1 /* Global */;
isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
if (previousToken !== contextToken) {
ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
@@ -82722,9 +83063,7 @@ var ts;
previousToken.getStart() :
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
- if (isGlobalCompletionScope(scopeNode)) {
- completionKind = 1 /* Global */;
- }
+ isInSnippetScope = isSnippetScope(scopeNode);
var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
@@ -82744,7 +83083,7 @@ var ts;
filterGlobalCompletion(symbols);
return true;
}
- function isGlobalCompletionScope(scopeNode) {
+ function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
case 272 /* SourceFile */:
case 200 /* TemplateExpression */:
@@ -82920,7 +83259,7 @@ var ts;
|| containingNodeKind === 159 /* IndexSignature */ // [ | : string ]
|| containingNodeKind === 146 /* ComputedPropertyName */; // [ | /* this can become an index signature */
case 129 /* ModuleKeyword */: // module |
- case 130 /* NamespaceKeyword */:// namespace |
+ case 130 /* NamespaceKeyword */: // namespace |
return true;
case 23 /* DotToken */:
return containingNodeKind === 237 /* ModuleDeclaration */; // module A.|
@@ -82995,7 +83334,7 @@ var ts;
isNewIdentifierLocation = false;
var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
if (!ts.isVariableLike(rootDeclaration))
- throw ts.Debug.fail("Root declaration is not variable-like.");
+ return ts.Debug.fail("Root declaration is not variable-like.");
// We don't want to complete using the type acquired by the shape
// of the binding pattern; we are only interested in types acquired
// through type declaration or inference.
@@ -83115,7 +83454,7 @@ var ts;
if (contextToken) {
switch (contextToken.kind) {
case 17 /* OpenBraceToken */: // const x = { |
- case 26 /* CommaToken */:// const x = { a: 0, |
+ case 26 /* CommaToken */: // const x = { a: 0, |
var parent = contextToken.parent;
if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) {
return parent;
@@ -83133,7 +83472,7 @@ var ts;
if (contextToken) {
switch (contextToken.kind) {
case 17 /* OpenBraceToken */: // import { |
- case 26 /* CommaToken */:// import { a as 0, |
+ case 26 /* CommaToken */: // import { a as 0, |
switch (contextToken.parent.kind) {
case 245 /* NamedImports */:
case 249 /* NamedExports */:
@@ -83161,7 +83500,7 @@ var ts;
function tryGetClassLikeCompletionContainer(contextToken) {
if (contextToken) {
switch (contextToken.kind) {
- case 17 /* OpenBraceToken */:// class c { |
+ case 17 /* OpenBraceToken */: // class c { |
if (ts.isClassLike(contextToken.parent)) {
return contextToken.parent;
}
@@ -83362,7 +83701,7 @@ var ts;
case 110 /* LetKeyword */:
case 76 /* ConstKeyword */:
case 116 /* YieldKeyword */:
- case 139 /* TypeKeyword */:// type htm|
+ case 139 /* TypeKeyword */: // type htm|
return true;
}
// If the previous token is keyword correspoding to class member completion keyword
@@ -83477,7 +83816,7 @@ var ts;
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
var name = ts.getNameOfDeclaration(m);
- existingName = ts.getEscapedTextOfIdentifierOrLiteral(name);
+ existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
existingMemberNames.set(existingName, true);
}
@@ -83581,10 +83920,10 @@ var ts;
// TODO: GH#18169
return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
case 2 /* PropertyAccess */:
- case 5 /* None */:
case 1 /* Global */:
// Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547
return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true };
+ case 5 /* None */:
case 4 /* String */:
return validIdentiferResult;
default:
@@ -83757,30 +84096,17 @@ var ts;
}
function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken);
- return referenceEntries && convertReferencedSymbols(referenceEntries);
- }
- function convertReferencedSymbols(referenceEntries) {
- var fileNameToDocumentHighlights = ts.createMap();
- for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
- var entry = referenceEntries_1[_i];
- var _a = ts.FindAllReferences.toHighlightSpan(entry), fileName = _a.fileName, span_12 = _a.span;
- var highlightSpans = fileNameToDocumentHighlights.get(fileName);
- if (!highlightSpans) {
- fileNameToDocumentHighlights.set(fileName, highlightSpans = []);
- }
- highlightSpans.push(span_12);
- }
- return ts.arrayFrom(fileNameToDocumentHighlights.entries(), function (_a) {
+ 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) {
var fileName = _a[0], highlightSpans = _a[1];
return ({ fileName: fileName, highlightSpans: highlightSpans });
});
}
function getSyntacticDocumentHighlights(node, sourceFile) {
var highlightSpans = getHighlightSpans(node, sourceFile);
- if (!highlightSpans || highlightSpans.length === 0) {
- return undefined;
- }
- return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
+ return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
}
function getHighlightSpans(node, sourceFile) {
switch (node.kind) {
@@ -84321,7 +84647,9 @@ var ts;
}
else if (ts.isDefaultImport(direct)) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(direct);
- addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports
+ if (!isAvailableThroughGlobal) {
+ addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports
+ }
directImports.push(direct);
}
else {
@@ -84473,7 +84801,7 @@ var ts;
if (propertyName) {
// This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference.
singleReferences.push(propertyName);
- if (!isForRename) {
+ if (!isForRename) { // If renaming `foo`, don't touch `bar`, just `foo`.
// Search locally for `bar`.
addSearch(name, checker.getSymbolAtLocation(name));
}
@@ -84648,12 +84976,15 @@ var ts;
return exportInfo(symbol, getExportKindForDeclaration(exportNode));
}
}
+ // If we are in `export = a;` or `export default a;`, `parent` is the export assignment.
else if (ts.isExportAssignment(parent)) {
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(parent.parent)) {
return getExportAssignmentExport(parent.parent);
}
+ // Similar for `module.exports =` and `exports.A =`.
else if (ts.isBinaryExpression(parent)) {
return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true);
}
@@ -84724,10 +85055,10 @@ var ts;
return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol));
}
var decl = importedSymbol.valueDeclaration;
- if (ts.isExportAssignment(decl)) {
+ if (ts.isExportAssignment(decl)) { // `export = class {}`
return ts.Debug.assertDefined(decl.expression.symbol);
}
- else if (ts.isBinaryExpression(decl)) {
+ else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}`
return ts.Debug.assertDefined(decl.right.symbol);
}
return ts.Debug.fail();
@@ -84804,8 +85135,8 @@ var ts;
if (parent.kind === 272 /* SourceFile */) {
return parent;
}
- ts.Debug.assert(parent.kind === 238 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent));
- return parent.parent;
+ ts.Debug.assert(parent.kind === 238 /* ModuleBlock */);
+ return ts.cast(parent.parent, isAmbientModuleDeclaration);
}
function isAmbientModuleDeclaration(node) {
return node.kind === 237 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */;
@@ -84827,12 +85158,13 @@ var ts;
}
FindAllReferences.nodeEntry = nodeEntry;
function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
- var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position);
+ var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, /*options*/ {});
var checker = program.getTypeChecker();
return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) {
var definition = _a.definition, references = _a.references;
// Only include referenced symbols that have a valid definition.
- return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) };
+ return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) };
});
}
FindAllReferences.findReferencedSymbols = findReferencedSymbols;
@@ -84868,8 +85200,8 @@ var ts;
}
}
function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) {
- var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options));
- return ts.map(x, toReferenceEntry);
+ var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry);
}
FindAllReferences.findReferencedEntries = findReferencedEntries;
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) {
@@ -84877,46 +85209,41 @@ var ts;
return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options));
}
FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode;
- function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) {
- var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
- return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options);
- }
function flattenEntries(referenceSymbols) {
return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
}
- function definitionToReferencedSymbolDefinitionInfo(def, checker) {
+ function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
var info = (function () {
switch (def.type) {
case "symbol": {
- var symbol = def.symbol, node_3 = def.node;
- var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
+ var symbol = def.symbol;
+ var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
var name_4 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 };
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 };
}
case "label": {
- var node_4 = def.node;
- return { node: node_4, name: node_4.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_4.text, ts.SymbolDisplayPartKind.text)] };
+ var node_3 = def.node;
+ return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
}
case "keyword": {
- var node_5 = def.node;
- var name_5 = ts.tokenToString(node_5.kind);
- return { node: node_5, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ var node_4 = def.node;
+ var name_5 = ts.tokenToString(node_4.kind);
+ return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
}
case "this": {
- var node_6 = def.node;
- var symbol = checker.getSymbolAtLocation(node_6);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_6.getSourceFile(), ts.getContainerNode(node_6), node_6).displayParts;
- return { node: node_6, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
+ var node_5 = def.node;
+ var symbol = checker.getSymbolAtLocation(node_5);
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts;
+ return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
case "string": {
- var node_7 = def.node;
- return { node: node_7, name: node_7.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_7), ts.SymbolDisplayPartKind.stringLiteral)] };
+ var node_6 = def.node;
+ return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
}
+ default:
+ return ts.Debug.assertNever(def);
}
})();
- if (!info) {
- return undefined;
- }
var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts;
var sourceFile = node.getSourceFile();
return {
@@ -84929,8 +85256,10 @@ var ts;
displayParts: displayParts
};
}
- function getDefinitionKindAndDisplayParts(symbol, node, checker) {
- var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
+ function getDefinitionKindAndDisplayParts(symbol, checker, node) {
+ var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol);
+ var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node;
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
return { displayParts: displayParts, kind: symbolKind };
}
function toReferenceEntry(entry) {
@@ -84961,7 +85290,7 @@ var ts;
function implementationKindDisplayParts(node, checker) {
var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node);
if (symbol) {
- return getDefinitionKindAndDisplayParts(symbol, node, checker);
+ return getDefinitionKindAndDisplayParts(symbol, checker, node);
}
else if (node.kind === 182 /* ObjectLiteralExpression */) {
return {
@@ -85086,10 +85415,7 @@ var ts;
ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
- return [{
- definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration },
- references: references
- }];
+ return [{ definition: { type: "symbol", symbol: symbol }, references: references }];
}
/** getReferencedSymbols for special node kinds. */
function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
@@ -85097,17 +85423,15 @@ var ts;
return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken);
}
// Labels
- if (ts.isLabelName(node)) {
- if (ts.isJumpStatementTarget(node)) {
- var labelDefinition = ts.getTargetLabel(node.parent, node.text);
- // if we have a label definition, look within its statement for references, if not, then
- // the label is undefined and we have no results..
- return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
- }
- else {
- // it is a label definition and not a target, search within the parent labeledStatement
- return getLabelReferencesInNode(node.parent, node);
- }
+ if (ts.isJumpStatementTarget(node)) {
+ var labelDefinition = ts.getTargetLabel(node.parent, node.text);
+ // if we have a label definition, look within its statement for references, if not, then
+ // the label is undefined and we have no results..
+ return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
+ }
+ else if (ts.isLabelOfLabeledStatement(node)) {
+ // it is a label definition and not a target, search within the parent labeledStatement
+ return getLabelReferencesInNode(node.parent, node);
}
if (ts.isThis(node)) {
return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
@@ -85121,11 +85445,11 @@ var ts;
function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) {
symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
// Compute the meaning from the location and the symbol it references
- var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations);
+ var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol);
var result = [];
var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result);
if (node.kind === 79 /* DefaultKeyword */) {
- addReference(node, symbol, node, state);
+ addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
else {
@@ -85229,7 +85553,11 @@ var ts;
this.symbolIdToReferences = [];
// Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
this.sourceFileToSeenSymbols = [];
+ this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; });
}
+ State.prototype.includesSourceFile = function (sourceFile) {
+ return this.includedSourceFiles.has(sourceFile.fileName);
+ };
/** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
State.prototype.getImportSearches = function (exportSymbol, exportInfo) {
if (!this.importTracker)
@@ -85243,11 +85571,11 @@ var ts;
// Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`.
// The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form
// here appears to be intentional).
- var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b;
+ var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, allSearchSymbols = searchOptions.allSearchSymbols;
var escapedText = ts.escapeLeadingUnderscores(text);
var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
return {
- location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents,
+ symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents,
includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; },
};
};
@@ -85255,12 +85583,12 @@ var ts;
* Callback to add references for a particular searched symbol.
* This initializes a reference group, so only call this if you will add at least one reference.
*/
- State.prototype.referenceAdder = function (searchSymbol, searchLocation) {
+ State.prototype.referenceAdder = function (searchSymbol) {
var symbolId = ts.getSymbolId(searchSymbol);
var references = this.symbolIdToReferences[symbolId];
if (!references) {
references = this.symbolIdToReferences[symbolId] = [];
- this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references });
+ this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references });
}
return function (node) { return references.push(FindAllReferences.nodeEntry(node)); };
};
@@ -85285,7 +85613,7 @@ var ts;
var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers;
// For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file.
if (singleReferences.length) {
- var addRef = state.referenceAdder(exportSymbol, exportLocation);
+ var addRef = state.referenceAdder(exportSymbol);
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
addRef(singleRef);
@@ -85321,7 +85649,10 @@ var ts;
function searchForImportedSymbol(symbol, state) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- getReferencesInSourceFile(declaration.getSourceFile(), state.createSearch(declaration, symbol, 0 /* Import */), state);
+ var exportingFile = declaration.getSourceFile();
+ if (state.includesSourceFile(exportingFile)) {
+ getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state);
+ }
}
}
/** Search for all occurences of an identifier in a source file (and filter out the ones that match). */
@@ -85421,6 +85752,17 @@ var ts;
// So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.)
return exposedByParent ? scope.getSourceFile() : scope;
}
+ /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
+ function isSymbolReferencedInFile(definition, checker, sourceFile) {
+ var symbol = checker.getSymbolAtLocation(definition);
+ if (!symbol)
+ return true; // Be lenient with invalid code.
+ return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) {
+ var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), ts.isIdentifier);
+ return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol;
+ });
+ }
+ Core.isSymbolReferencedInFile = isSymbolReferencedInFile;
function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) {
if (container === void 0) { container = sourceFile; }
var positions = [];
@@ -85451,18 +85793,13 @@ var ts;
return positions;
}
function getLabelReferencesInNode(container, targetLabel) {
- var references = [];
var sourceFile = container.getSourceFile();
var labelName = targetLabel.text;
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container);
- for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) {
- var position = possiblePositions_1[_i];
+ var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) {
var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
// Only pick labels that are either the target label, or have a target that is the target label
- if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) {
- references.push(FindAllReferences.nodeEntry(node));
- }
- }
+ return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined;
+ });
return [{ definition: { type: "label", node: targetLabel }, references: references }];
}
function isValidReferencePosition(node, searchSymbolName) {
@@ -85482,24 +85819,15 @@ var ts;
}
}
function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) {
- var references = [];
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
+ var references = ts.flatMap(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references);
- }
+ return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) {
+ var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined;
+ });
+ });
return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined;
}
- function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) {
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile);
- for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) {
- var position = possiblePositions_2[_i];
- var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
- if (referenceLocation.kind === kind) {
- references.push(FindAllReferences.nodeEntry(referenceLocation));
- }
- }
- }
function getReferencesInSourceFile(sourceFile, search, state) {
state.cancellationToken.throwIfCancellationRequested();
return getReferencesInContainer(sourceFile, sourceFile, search, state);
@@ -85557,7 +85885,7 @@ var ts;
}
switch (state.specialSearchKind) {
case 0 /* None */:
- addReference(referenceLocation, relatedSymbol, search.location, state);
+ addReference(referenceLocation, relatedSymbol, state);
break;
case 1 /* Constructor */:
addConstructorReferences(referenceLocation, sourceFile, search, state);
@@ -85587,7 +85915,7 @@ var ts;
addRef();
}
if (!state.options.isForRename && state.markSeenReExportRHS(name)) {
- addReference(name, referenceSymbol, name, state);
+ addReference(name, referenceSymbol, state);
}
}
else {
@@ -85609,7 +85937,7 @@ var ts;
searchForImportedSymbol(imported, state);
}
function addRef() {
- addReference(referenceLocation, localSymbol, search.location, state);
+ addReference(referenceLocation, localSymbol, state);
}
}
function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
@@ -85654,11 +85982,11 @@ var ts;
* position of property accessing, the referenceEntry of such position will be handled in the first case.
*/
if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) {
- addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state);
+ addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state);
}
}
- function addReference(referenceLocation, relatedSymbol, searchLocation, state) {
- var addRef = state.referenceAdder(relatedSymbol, searchLocation);
+ function addReference(referenceLocation, relatedSymbol, state) {
+ var addRef = state.referenceAdder(relatedSymbol);
if (state.options.implementations) {
addImplementationReferences(referenceLocation, addRef, state);
}
@@ -85669,9 +85997,9 @@ var ts;
/** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */
function addConstructorReferences(referenceLocation, sourceFile, search, state) {
if (ts.isNewExpressionTarget(referenceLocation)) {
- addReference(referenceLocation, search.symbol, search.location, state);
+ addReference(referenceLocation, search.symbol, state);
}
- var pusher = function () { return state.referenceAdder(search.symbol, search.location); };
+ var pusher = function () { return state.referenceAdder(search.symbol); };
if (ts.isClassLike(referenceLocation.parent)) {
ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation);
// This is the class declaration containing the constructor.
@@ -85686,11 +86014,11 @@ var ts;
}
}
function addClassStaticThisReferences(referenceLocation, search, state) {
- addReference(referenceLocation, search.symbol, search.location, state);
- if (ts.isClassLike(referenceLocation.parent)) {
+ addReference(referenceLocation, search.symbol, state);
+ if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) {
ts.Debug.assert(referenceLocation.parent.name === referenceLocation);
// This is the class declaration.
- addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location));
+ addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol));
}
}
function addStaticThisReferences(classLike, pusher) {
@@ -85815,7 +86143,7 @@ var ts;
return result;
}
function getContainingTypeReference(node) {
- var topLevelTypeReference = undefined;
+ var topLevelTypeReference;
while (node) {
if (ts.isTypeNode(node)) {
topLevelTypeReference = node;
@@ -85943,24 +86271,19 @@ var ts;
default:
return undefined;
}
- var references = [];
var sourceFile = searchSpaceNode.getSourceFile();
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode);
- for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) {
- var position = possiblePositions_3[_i];
+ var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) {
var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
if (!node || node.kind !== 97 /* SuperKeyword */) {
- continue;
+ return;
}
var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false);
// If we have a 'super' container, we must have an enclosing class.
// Now make sure the owning class is the same as the search-space
// and has the same static qualifier as the original 'super's owner.
- if (container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) {
- references.push(FindAllReferences.nodeEntry(node));
- }
- }
- return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol, node: superKeyword }, references: references }];
+ return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined;
+ });
+ return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }];
}
function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false);
@@ -85995,18 +86318,11 @@ var ts;
return undefined;
}
var references = [];
- var possiblePositions;
- if (searchSpaceNode.kind === 272 /* SourceFile */) {
- ts.forEach(sourceFiles, function (sourceFile) {
- cancellationToken.throwIfCancellationRequested();
- possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this");
- getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, staticFlag, references);
- });
- }
- else {
- var sourceFile = searchSpaceNode.getSourceFile();
- possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode);
- getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, references);
+ for (var _i = 0, _a = searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ cancellationToken.throwIfCancellationRequested();
+ var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode);
+ getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFile : searchSpaceNode, positions, staticFlag, references);
}
return [{
definition: { type: "this", node: thisOrSuperKeyword },
@@ -86050,26 +86366,17 @@ var ts;
});
}
function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
- var references = [];
- for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
- var sourceFile = sourceFiles_7[_i];
+ var references = ts.flatMap(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text);
- getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references);
- }
+ return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) {
+ var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false), ts.isStringLiteral);
+ return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined;
+ });
+ });
return [{
definition: { type: "string", node: node },
references: references
}];
- function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) {
- for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) {
- var position = possiblePositions_4[_i];
- var node_8 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
- if (node_8 && node_8.kind === 9 /* StringLiteral */ && node_8.text === searchText) {
- references.push(FindAllReferences.nodeEntry(node_8, /*isInString*/ true));
- }
- }
- }
}
// For certain symbol kinds, we need to include other symbols in the search set.
// This is not needed when searching for re-exports.
@@ -86286,7 +86593,9 @@ var ts;
* module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module)
* do not intersect in any of the three spaces.
*/
- function getIntersectingMeaningFromDeclarations(meaning, declarations) {
+ function getIntersectingMeaningFromDeclarations(node, symbol) {
+ var meaning = ts.getMeaningFromLocation(node);
+ var declarations = symbol.declarations;
if (declarations) {
var lastIterationMeaning = void 0;
do {
@@ -86307,6 +86616,7 @@ var ts;
}
return meaning;
}
+ Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
function isImplementation(node) {
if (!node) {
return false;
@@ -86410,9 +86720,8 @@ var ts;
}
// Labels
if (ts.isJumpStatementTarget(node)) {
- var labelName = node.text;
- var label = ts.getTargetLabel(node.parent, labelName);
- return label ? [createDefinitionInfoFromName(label, "label" /* label */, labelName, /*containerName*/ undefined)] : undefined;
+ var label = ts.getTargetLabel(node.parent, node.text);
+ return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined;
}
var typeChecker = program.getTypeChecker();
var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
@@ -87351,7 +87660,7 @@ var ts;
case 6 /* NameContainsNonURISafeCharacters */:
return "Package name '" + typing + "' contains non URI safe characters";
case 0 /* Ok */:
- throw ts.Debug.fail(); // Shouldn't have called this.
+ return ts.Debug.fail(); // Shouldn't have called this.
default:
ts.Debug.assertNever(result);
}
@@ -87377,8 +87686,8 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) {
- var sourceFile = sourceFiles_8[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
_loop_8(sourceFile);
}
rawItems.sort(compareNavigateToItems);
@@ -87438,41 +87747,35 @@ var ts;
return true;
}
function tryAddSingleDeclarationName(declaration, containers) {
- if (declaration) {
- var name = ts.getNameOfDeclaration(declaration);
- if (name) {
- var text = ts.getTextOfIdentifierOrLiteral(name);
- if (text !== undefined) {
- containers.unshift(text);
- }
- else if (name.kind === 146 /* ComputedPropertyName */) {
- return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true);
- }
- else {
- // Don't know how to add this.
- return false;
- }
- }
+ var name = ts.getNameOfDeclaration(declaration);
+ if (name && ts.isPropertyNameLiteral(name)) {
+ containers.unshift(ts.getTextOfIdentifierOrLiteral(name));
+ return true;
+ }
+ else if (name && name.kind === 146 /* ComputedPropertyName */) {
+ return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true);
+ }
+ else {
+ // Don't know how to add this.
+ return false;
}
- return true;
}
// Only added the names of computed properties if they're simple dotted expressions, like:
//
// [X.Y.Z]() { }
function tryAddComputedPropertyName(expression, containers, includeLastPortion) {
- var text = ts.getTextOfIdentifierOrLiteral(expression);
- if (text !== undefined) {
+ if (ts.isPropertyNameLiteral(expression)) {
+ var text = ts.getTextOfIdentifierOrLiteral(expression);
if (includeLastPortion) {
containers.unshift(text);
}
return true;
}
- if (expression.kind === 183 /* PropertyAccessExpression */) {
- var propertyAccess = expression;
+ if (ts.isPropertyAccessExpression(expression)) {
if (includeLastPortion) {
- containers.unshift(propertyAccess.name.text);
+ containers.unshift(expression.name.text);
}
- return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true);
+ return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true);
}
return false;
}
@@ -88111,16 +88414,20 @@ var ts;
if (node.name && ts.getFullWidth(node.name) > 0) {
return ts.declarationNameToString(node.name);
}
+ // See if it is a var initializer. If so, use the var name.
else if (node.parent.kind === 230 /* VariableDeclaration */) {
return ts.declarationNameToString(node.parent.name);
}
+ // See if it is of the form " = function(){...}". If so, use the text from the left-hand side.
else if (node.parent.kind === 198 /* BinaryExpression */ &&
node.parent.operatorToken.kind === 58 /* EqualsToken */) {
return nodeText(node.parent.left).replace(whiteSpaceRegex, "");
}
+ // See if it is a property assignment, and if so use the property name
else if (node.parent.kind === 268 /* PropertyAssignment */ && node.parent.name) {
return nodeText(node.parent.name);
}
+ // Default exports are named "default"
else if (ts.getModifierFlags(node) & 512 /* Default */) {
return "default";
}
@@ -88145,44 +88452,102 @@ var ts;
(function (ts) {
var OrganizeImports;
(function (OrganizeImports) {
- function organizeImports(sourceFile, formatContext, host) {
- // TODO (https://github.com/Microsoft/TypeScript/issues/10020): sort *within* ambient modules (find using isAmbientModule)
- // All of the old ImportDeclarations in the file, in syntactic order.
- var oldImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
- if (oldImportDecls.length === 0) {
- return [];
- }
- var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
- var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) {
- return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier);
- });
- var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
- return getExternalModuleName(importGroup[0].moduleSpecifier)
- ? coalesceImports(removeUnusedImports(importGroup))
- : importGroup;
- });
+ /**
+ * Organize imports by:
+ * 1) Removing unused imports
+ * 2) Coalescing imports from the same module
+ * 3) Sorting imports
+ */
+ function organizeImports(sourceFile, formatContext, host, program) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
- // Delete or replace the first import.
- if (newImportDecls.length === 0) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[0]);
- }
- else {
- // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
- changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: false,
- useNonAdjustedEndPosition: false,
- suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
- });
- }
- // Delete any subsequent imports.
- for (var i = 1; i < oldImportDecls.length; i++) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
+ // All of the old ImportDeclarations in the file, in syntactic order.
+ var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
+ organizeImportsWorker(topLevelImportDecls);
+ for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
+ var ambientModule = _a[_i];
+ var ambientModuleBody = getModuleBlock(ambientModule);
+ var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
+ organizeImportsWorker(ambientModuleImportDecls);
}
return changeTracker.getChanges();
+ function organizeImportsWorker(oldImportDecls) {
+ if (ts.length(oldImportDecls) === 0) {
+ return;
+ }
+ var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
+ var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
+ var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
+ return getExternalModuleName(importGroup[0].moduleSpecifier)
+ ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
+ : importGroup;
+ });
+ // Delete or replace the first import.
+ if (newImportDecls.length === 0) {
+ changeTracker.deleteNode(sourceFile, oldImportDecls[0]);
+ }
+ else {
+ // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
+ changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
+ useNonAdjustedStartPosition: false,
+ useNonAdjustedEndPosition: false,
+ suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
+ });
+ }
+ // Delete any subsequent imports.
+ for (var i = 1; i < oldImportDecls.length; i++) {
+ changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
+ }
+ }
}
OrganizeImports.organizeImports = organizeImports;
- function removeUnusedImports(oldImports) {
- return oldImports; // TODO (https://github.com/Microsoft/TypeScript/issues/10020)
+ function getModuleBlock(moduleDecl) {
+ var body = moduleDecl.body;
+ return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body));
+ }
+ function removeUnusedImports(oldImports, sourceFile, program) {
+ var typeChecker = program.getTypeChecker();
+ var jsxNamespace = typeChecker.getJsxNamespace();
+ var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx;
+ var usedImports = [];
+ for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
+ var importDecl = oldImports_1[_i];
+ var importClause = importDecl.importClause;
+ if (!importClause) {
+ // Imports without import clauses are assumed to be included for their side effects and are not removed.
+ usedImports.push(importDecl);
+ continue;
+ }
+ var name = importClause.name, namedBindings = importClause.namedBindings;
+ // Default import
+ if (name && !isDeclarationUsed(name)) {
+ name = undefined;
+ }
+ if (namedBindings) {
+ if (ts.isNamespaceImport(namedBindings)) {
+ // Namespace import
+ if (!isDeclarationUsed(namedBindings.name)) {
+ namedBindings = undefined;
+ }
+ }
+ else {
+ // List of named imports
+ var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.propertyName || e.name); });
+ if (newElements.length < namedBindings.elements.length) {
+ namedBindings = newElements.length
+ ? ts.updateNamedImports(namedBindings, newElements)
+ : undefined;
+ }
+ }
+ }
+ if (name || namedBindings) {
+ usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
+ }
+ }
+ return usedImports;
+ function isDeclarationUsed(identifier) {
+ // The JSX factory symbol is always used.
+ return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
+ }
}
function getExternalModuleName(specifier) {
return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier)
@@ -88197,7 +88562,7 @@ var ts;
if (importGroup.length === 0) {
return importGroup;
}
- var _a = getImportParts(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports;
+ var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports;
var coalescedImports = [];
if (importWithoutClause) {
coalescedImports.push(importWithoutClause);
@@ -88206,15 +88571,17 @@ var ts;
// produce two import declarations in this special case.
if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
// Add the namespace import to the existing default ImportDeclaration.
- var defaultImportClause = defaultImports[0].parent;
- coalescedImports.push(updateImportDeclarationAndClause(defaultImportClause, defaultImportClause.name, namespaceImports[0]));
+ var defaultImport = defaultImports[0];
+ coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings));
return coalescedImports;
}
- var sortedNamespaceImports = ts.stableSort(namespaceImports, function (n1, n2) { return compareIdentifiers(n1.name, n2.name); });
+ var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) {
+ return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name);
+ });
for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) {
var namespaceImport = sortedNamespaceImports_1[_i];
// Drop the name, if any
- coalescedImports.push(updateImportDeclarationAndClause(namespaceImport.parent, /*name*/ undefined, namespaceImport));
+ coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings));
}
if (defaultImports.length === 0 && namedImports.length === 0) {
return coalescedImports;
@@ -88222,30 +88589,37 @@ var ts;
var newDefaultImport;
var newImportSpecifiers = [];
if (defaultImports.length === 1) {
- newDefaultImport = defaultImports[0];
+ newDefaultImport = defaultImports[0].importClause.name;
}
else {
for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) {
var defaultImport = defaultImports_1[_b];
- newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport));
+ newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name));
}
}
- newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (n) { return n.elements; }));
+ newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
- var importClause = defaultImports.length > 0
- ? defaultImports[0].parent
- : namedImports[0].parent;
+ var importDecl = defaultImports.length > 0
+ ? defaultImports[0]
+ : namedImports[0];
var newNamedImports = sortedImportSpecifiers.length === 0
? undefined
: namedImports.length === 0
? ts.createNamedImports(sortedImportSpecifiers)
- : ts.updateNamedImports(namedImports[0], sortedImportSpecifiers);
- coalescedImports.push(updateImportDeclarationAndClause(importClause, newDefaultImport, newNamedImports));
+ : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers);
+ coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports));
return coalescedImports;
- function getImportParts(importGroup) {
+ /*
+ * Returns entire import declarations because they may already have been rewritten and
+ * may lack parent pointers. The desired parts can easily be recovered based on the
+ * categorization.
+ *
+ * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`.
+ */
+ function getCategorizedImports(importGroup) {
var importWithoutClause;
var defaultImports = [];
var namespaceImports = [];
@@ -88260,14 +88634,14 @@ var ts;
}
var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
if (name) {
- defaultImports.push(name);
+ defaultImports.push(importDeclaration);
}
if (namedBindings) {
if (ts.isNamespaceImport(namedBindings)) {
- namespaceImports.push(namedBindings);
+ namespaceImports.push(importDeclaration);
}
else {
- namedImports.push(namedBindings);
+ namedImports.push(importDeclaration);
}
}
}
@@ -88281,12 +88655,11 @@ var ts;
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseSensitive(s1.text, s2.text);
}
- function updateImportDeclarationAndClause(importClause, name, namedBindings) {
- var importDeclaration = importClause.parent;
- return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, name, namedBindings), importDeclaration.moduleSpecifier);
- }
}
OrganizeImports.coalesceImports = coalesceImports;
+ function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
+ return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
+ }
/* internal */ // Exported for testing
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
@@ -88339,8 +88712,8 @@ var ts;
continue;
}
if (!result[1]) {
- var span_13 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span_13, span_13, /*autoCollapse*/ false, result[2] || "#region"));
+ var span_12 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
+ regions.push(createOutliningSpan(span_12, span_12, /*autoCollapse*/ false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -88579,10 +88952,10 @@ var ts;
// But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
var wordSpans = getWordSpans(candidate);
for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
- var span_14 = wordSpans_1[_i];
- if (partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ true)) {
+ var span_13 = wordSpans_1[_i];
+ if (partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ true)) {
return createPatternMatch(PatternMatchKind.substring, punctuationStripped,
- /*isCaseSensitive:*/ partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ false));
+ /*isCaseSensitive:*/ partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ false));
}
}
}
@@ -88684,7 +89057,7 @@ var ts;
//
// Only if all words have some sort of match is the pattern considered matched.
var subWordTextChunks = segment.subWordTextChunks;
- var matches = undefined;
+ var matches;
for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) {
var subWordTextChunk = subWordTextChunks_1[_i];
// Try to match the candidate with this word
@@ -88732,8 +89105,8 @@ var ts;
// and I will both match in UI.
var currentCandidate = 0;
var currentChunkSpan = 0;
- var firstMatch = undefined;
- var contiguous = undefined;
+ var firstMatch;
+ var contiguous;
while (true) {
// Let's consider our termination cases
if (currentChunkSpan === chunkCharacterSpans.length) {
@@ -89033,11 +89406,18 @@ var ts;
function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
if (readImportFiles === void 0) { readImportFiles = true; }
if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
- var referencedFiles = [];
- var typeReferenceDirectives = [];
+ var pragmaContext = {
+ languageVersion: 1 /* ES5 */,
+ pragmas: undefined,
+ checkJsDirective: undefined,
+ referencedFiles: [],
+ typeReferenceDirectives: [],
+ amdDependencies: [],
+ hasNoDefaultLib: undefined,
+ moduleName: undefined
+ };
var importedFiles = [];
var ambientExternalModules;
- var isNoDefaultLib = false;
var braceNesting = 0;
// assume that text represent an external module if it contains at least one top level import/export
// ambient modules that are found inside external modules are interpreted as module augmentations
@@ -89052,23 +89432,6 @@ var ts;
}
return token;
}
- function processTripleSlashDirectives() {
- var commentRanges = ts.getLeadingCommentRanges(sourceText, 0);
- ts.forEach(commentRanges, function (commentRange) {
- var comment = sourceText.substring(commentRange.pos, commentRange.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange);
- if (referencePathMatchResult) {
- isNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var fileReference = referencePathMatchResult.fileReference;
- if (fileReference) {
- var collection = referencePathMatchResult.isTypeReferenceDirective
- ? typeReferenceDirectives
- : referencedFiles;
- collection.push(fileReference);
- }
- }
- });
- }
function getFileReference() {
var fileName = ts.scanner.getTokenValue();
var pos = ts.scanner.getTokenPos();
@@ -89329,7 +89692,8 @@ var ts;
if (readImportFiles) {
processImports();
}
- processTripleSlashDirectives();
+ ts.processCommentPragmas(pragmaContext, sourceText);
+ ts.processPragmasIntoFields(pragmaContext, ts.noop);
if (externalModule) {
// for external modules module all nested ambient modules are augmentations
if (ambientExternalModules) {
@@ -89339,7 +89703,7 @@ var ts;
importedFiles.push(decl.ref);
}
}
- return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined };
+ return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined };
}
else {
// for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
@@ -89358,7 +89722,7 @@ var ts;
}
}
}
- return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames };
+ return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
}
}
ts.preProcessFile = preProcessFile;
@@ -89389,22 +89753,17 @@ var ts;
var symbol = typeChecker.getSymbolAtLocation(node);
// Only allow a symbol to be renamed if it actually has at least one declaration.
if (symbol) {
- var declarations = symbol.getDeclarations();
+ var declarations = symbol.declarations;
if (declarations && declarations.length > 0) {
// Disallow rename for elements that are defined in the standard TypeScript library.
- if (ts.some(declarations, isDefinedInLibraryFile)) {
+ if (declarations.some(isDefinedInLibraryFile)) {
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";
- if (node.kind === 71 /* Identifier */ &&
- node.originalKeywordKind === 79 /* DefaultKeyword */ &&
- symbol.parent.flags & 1536 /* Module */) {
+ if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) {
return undefined;
}
var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
- if (!kind) {
- return undefined;
- }
var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */)
? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
: undefined;
@@ -89413,12 +89772,11 @@ var ts;
return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
}
}
- else if (node.kind === 9 /* StringLiteral */) {
+ else if (ts.isStringLiteral(node)) {
if (isDefinedInLibraryFile(node)) {
return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
}
- var displayName = ts.stripQuotes(node.text);
- return getRenameInfoSuccess(displayName, displayName, "var" /* variableElement */, "" /* none */, node, sourceFile);
+ return getRenameInfoSuccess(node.text, node.text, "var" /* variableElement */, "" /* none */, node, sourceFile);
}
}
function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
@@ -89876,6 +90234,63 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ function computeSuggestionDiagnostics(sourceFile, program) {
+ program.getSemanticDiagnostics(sourceFile);
+ var checker = program.getDiagnosticsProducingTypeChecker();
+ var diags = [];
+ if (sourceFile.commonJsModuleIndicator) {
+ diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
+ }
+ var isJsFile = ts.isSourceFileJavaScript(sourceFile);
+ function check(node) {
+ switch (node.kind) {
+ case 232 /* FunctionDeclaration */:
+ case 190 /* FunctionExpression */:
+ if (isJsFile) {
+ var symbol = node.symbol;
+ if (symbol.members && (symbol.members.size > 0)) {
+ diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
+ }
+ }
+ break;
+ }
+ if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) {
+ diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
+ }
+ node.forEachChild(check);
+ }
+ check(sourceFile);
+ if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
+ for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
+ var importNode = _a[_i];
+ var name = importNameForConvertToDefaultImport(importNode.parent);
+ if (!name)
+ continue;
+ var module = ts.getResolvedModule(sourceFile, importNode.text);
+ var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
+ if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
+ diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
+ }
+ }
+ }
+ return diags.concat(checker.getSuggestionDiagnostics(sourceFile));
+ }
+ ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
+ function importNameForConvertToDefaultImport(node) {
+ if (ts.isExternalModuleReference(node)) {
+ return node.parent.name;
+ }
+ if (ts.isImportDeclaration(node)) {
+ var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier;
+ return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier)
+ ? importClause.namedBindings.name
+ : undefined;
+ }
+ }
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var SymbolDisplay;
(function (SymbolDisplay) {
@@ -90085,7 +90500,7 @@ var ts;
}
}
else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration
- (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) {
+ (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* 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
@@ -91363,7 +91778,7 @@ var ts;
// case SyntaxKind.ConstructorDeclaration:
// case SyntaxKind.SimpleArrowFunctionExpression:
// case SyntaxKind.ParenthesizedArrowFunctionExpression:
- case 234 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one
+ case 234 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one
return true;
}
return false;
@@ -93165,26 +93580,14 @@ var ts;
function isControlFlowEndingStatement(kind, parent) {
switch (kind) {
case 223 /* ReturnStatement */:
- case 227 /* ThrowStatement */:
- switch (parent.kind) {
- case 211 /* Block */:
- var grandParent = parent.parent;
- switch (grandParent && grandParent.kind) {
- case 232 /* FunctionDeclaration */:
- case 190 /* FunctionExpression */:
- // We may want to write inner functions after this.
- return false;
- default:
- return true;
- }
- case 264 /* CaseClause */:
- case 265 /* DefaultClause */:
- case 272 /* SourceFile */:
- case 238 /* ModuleBlock */:
- return true;
- default:
- throw ts.Debug.fail();
+ case 227 /* ThrowStatement */: {
+ if (parent.kind !== 211 /* Block */) {
+ return true;
}
+ var grandParent = parent.parent;
+ // In a function, we may want to write inner functions after this.
+ return !(grandParent && grandParent.kind === 190 /* FunctionExpression */ || grandParent.kind === 232 /* FunctionDeclaration */);
+ }
case 221 /* ContinueStatement */:
case 222 /* BreakStatement */:
return true;
@@ -93322,10 +93725,9 @@ var ts;
}
var ChangeTracker = /** @class */ (function () {
/** Public for tests only. Other callers should use `ChangeTracker.with`. */
- function ChangeTracker(newLineCharacter, formatContext, validator) {
+ function ChangeTracker(newLineCharacter, formatContext) {
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
- this.validator = validator;
this.changes = [];
this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
// Map from class id to nodes to insert at the start
@@ -93464,10 +93866,10 @@ var ts;
if (ts.isStatement(before) || ts.isClassElement(before)) {
return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
}
- else if (ts.isVariableDeclaration(before)) {
+ else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2;
return { suffix: ", " };
}
- throw ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
+ return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
};
ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
var firstStatement = ts.firstOrUndefined(ctr.body.statements);
@@ -93544,7 +93946,7 @@ var ts;
else if (ts.isVariableDeclaration(node)) {
return { prefix: ", " };
}
- throw ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it
+ return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it
};
/**
* This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
@@ -93695,92 +94097,83 @@ var ts;
_this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true });
});
};
- ChangeTracker.prototype.getChanges = function () {
- var _this = this;
+ /**
+ * Note: after calling this, the TextChanges object must be discarded!
+ * @param validate only for tests
+ * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions,
+ * so we can only call this once and can't get the non-formatted text separately.
+ */
+ ChangeTracker.prototype.getChanges = function (validate) {
this.finishInsertNodeAtClassStart();
- return ts.group(this.changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
- var sourceFile = changesInFile[0].sourceFile;
- var textChanges = ChangeTracker.normalize(changesInFile).map(function (c) {
- return ts.createTextChange(ts.createTextSpanFromRange(c.range), _this.computeNewText(c, sourceFile));
- });
- return { fileName: sourceFile.fileName, textChanges: textChanges };
- });
- };
- ChangeTracker.prototype.computeNewText = function (change, sourceFile) {
- var _this = this;
- if (change.kind === ChangeKind.Remove) {
- // deletion case
- return "";
- }
- var options = change.options || {};
- var text;
- var pos = change.range.pos;
- var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos;
- if (change.kind === ChangeKind.ReplaceWithMultipleNodes) {
- var lastIndex_1 = change.nodes.length - 1;
- var parts = change.nodes.map(function (n, index) {
- var formatted = _this.getFormattedTextOfNode(n, sourceFile, pos, options);
- return index === lastIndex_1 || ts.endsWith(formatted, _this.newLineCharacter)
- ? formatted
- : (formatted + _this.newLineCharacter);
- });
- text = parts.join("");
- }
- else {
- ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode");
- text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options);
- }
- // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
- text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, "");
- return (options.prefix || "") + text + (options.suffix || "");
- };
- ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) {
- var nonformattedText = getNonformattedText(node, sourceFile, this.newLineCharacter);
- if (this.validator) {
- this.validator(nonformattedText);
- }
- var formatOptions = this.formatContext.options;
- var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos;
- var initialIndentation = options.indentation !== undefined
- ? options.indentation
- : (options.useIndentationFromFile !== false)
- ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter))
- : 0;
- var delta = options.delta !== undefined
- ? options.delta
- : ts.formatting.SmartIndenter.shouldIndentChildNode(node)
- ? (formatOptions.indentSize || 0)
- : 0;
- return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.formatContext);
- };
- ChangeTracker.normalize = function (changes) {
- // order changes by start position
- var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; });
- // verify that change intervals do not overlap, except possibly at end points.
- for (var i = 0; i < normalized.length - 2; i++) {
- ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos);
- }
- return normalized;
+ return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
};
return ChangeTracker;
}());
textChanges_1.ChangeTracker = ChangeTracker;
- function getNonformattedText(node, sourceFile, newLine) {
- var writer = new Writer(newLine);
- var printer = ts.createPrinter({ newLine: newLine === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */ }, writer);
- printer.writeNode(4 /* Unspecified */, node, sourceFile, writer);
- return { text: writer.getText(), node: assignPositionsToNode(node) };
- }
- function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, formatContext) {
- var lineMap = ts.computeLineStarts(nonFormattedText.text);
- var file = {
- text: nonFormattedText.text,
- lineMap: lineMap,
- getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); }
- };
- var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext);
- return applyChanges(nonFormattedText.text, changes);
- }
+ var changesToText;
+ (function (changesToText) {
+ function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
+ return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
+ var sourceFile = changesInFile[0].sourceFile;
+ // order changes by start position
+ var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
+ var _loop_10 = 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 - 2; i++) {
+ _loop_10(i);
+ }
+ var textChanges = normalized.map(function (c) {
+ return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
+ });
+ return { fileName: sourceFile.fileName, textChanges: textChanges };
+ });
+ }
+ changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
+ if (change.kind === ChangeKind.Remove) {
+ return "";
+ }
+ var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos;
+ var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); };
+ var text = change.kind === ChangeKind.ReplaceWithMultipleNodes
+ ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter)
+ : format(change.node);
+ // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
+ var noIndent = (options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, "");
+ return (options.prefix || "") + noIndent + (options.suffix || "");
+ }
+ /** Note: this may mutate `nodeIn`. */
+ function getFormattedTextOfNode(nodeIn, sourceFile, pos, options, newLineCharacter, formatContext, validate) {
+ var _a = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _a.node, text = _a.text;
+ if (validate)
+ validate(node, text);
+ var formatOptions = formatContext.options;
+ var initialIndentation = options.indentation !== undefined
+ ? options.indentation
+ : (options.useIndentationFromFile !== false)
+ ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, options.prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos)
+ : 0;
+ var delta = options.delta !== undefined
+ ? options.delta
+ : ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn)
+ ? (formatOptions.indentSize || 0)
+ : 0;
+ var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } };
+ var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext);
+ return applyChanges(text, changes);
+ }
+ /** Note: output node may be mutated input node. */
+ function getNonformattedText(node, sourceFile, newLineCharacter) {
+ var writer = new Writer(newLineCharacter);
+ var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */;
+ ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer);
+ return { text: writer.getText(), node: assignPositionsToNode(node) };
+ }
+ })(changesToText || (changesToText = {}));
function applyChanges(text, changes) {
for (var i = changes.length - 1; i >= 0; i--) {
var change = changes[i];
@@ -94059,7 +94452,7 @@ var ts;
codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges;
function eachDiagnostic(_a, errorCodes, cb) {
var program = _a.program, sourceFile = _a.sourceFile;
- for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) {
+ for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) {
var diag = _b[_i];
if (ts.contains(errorCodes, diag.code)) {
cb(diag);
@@ -94125,6 +94518,831 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "annotateWithTypeFromJSDoc";
+ var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var decl = getDeclaration(context.sourceFile, context.span.start);
+ if (!decl)
+ return;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Annotate_with_type_from_JSDoc);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); });
+ return [{ description: description, changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var decl = getDeclaration(diag.file, diag.start);
+ if (decl)
+ doChange(changes, diag.file, decl);
+ }); },
+ });
+ function getDeclaration(file, pos) {
+ var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false);
+ // For an arrow function with no name, 'name' lands on the first parameter.
+ return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
+ }
+ function parameterShouldGetTypeFromJSDoc(node) {
+ return isDeclarationWithType(node) && hasUsableJSDoc(node);
+ }
+ codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc;
+ function hasUsableJSDoc(decl) {
+ return ts.isFunctionLikeDeclaration(decl)
+ ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl))
+ : !decl.type && !!ts.getJSDocType(decl);
+ }
+ function doChange(changes, sourceFile, decl) {
+ if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
+ ts.findAncestor(decl, ts.isFunctionLike);
+ var fn = ts.findAncestor(decl, ts.isFunctionLikeDeclaration);
+ var functionWithType = addTypesToFunctionLike(fn);
+ ts.suppressLeadingAndTrailingTrivia(functionWithType);
+ changes.replaceNode(sourceFile, fn, functionWithType, ts.textChanges.useNonAdjustedPositions);
+ return;
+ }
+ else {
+ var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix
+ ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix.
+ var declarationWithType = addType(decl, transformJSDocType(jsdocType));
+ ts.suppressLeadingAndTrailingTrivia(declarationWithType);
+ changes.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions);
+ }
+ }
+ function isDeclarationWithType(node) {
+ return ts.isFunctionLikeDeclaration(node) ||
+ node.kind === 230 /* VariableDeclaration */ ||
+ node.kind === 150 /* PropertySignature */ ||
+ node.kind === 151 /* PropertyDeclaration */;
+ }
+ function addTypesToFunctionLike(decl) {
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, /*checkJSDoc*/ true);
+ var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, /*checkJSDoc*/ true)), p.initializer); });
+ var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, /*checkJSDoc*/ true));
+ switch (decl.kind) {
+ case 232 /* FunctionDeclaration */:
+ return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
+ case 154 /* Constructor */:
+ return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body);
+ case 190 /* FunctionExpression */:
+ return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
+ case 191 /* ArrowFunction */:
+ return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body);
+ case 153 /* MethodDeclaration */:
+ return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body);
+ case 155 /* GetAccessor */:
+ return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body);
+ case 156 /* SetAccessor */:
+ return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body);
+ default:
+ return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind);
+ }
+ }
+ function addType(decl, jsdocType) {
+ switch (decl.kind) {
+ case 230 /* VariableDeclaration */:
+ return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer);
+ case 150 /* PropertySignature */:
+ return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
+ case 151 /* PropertyDeclaration */:
+ return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
+ default:
+ return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind);
+ }
+ }
+ function transformJSDocType(node) {
+ if (node === undefined) {
+ return undefined;
+ }
+ switch (node.kind) {
+ case 275 /* JSDocAllType */:
+ case 276 /* JSDocUnknownType */:
+ return ts.createTypeReferenceNode("any", ts.emptyArray);
+ case 279 /* JSDocOptionalType */:
+ return transformJSDocOptionalType(node);
+ case 278 /* JSDocNonNullableType */:
+ return transformJSDocType(node.type);
+ case 277 /* JSDocNullableType */:
+ return transformJSDocNullableType(node);
+ case 281 /* JSDocVariadicType */:
+ return transformJSDocVariadicType(node);
+ case 280 /* JSDocFunctionType */:
+ return transformJSDocFunctionType(node);
+ case 148 /* Parameter */:
+ return transformJSDocParameter(node);
+ case 161 /* TypeReference */:
+ return transformJSDocTypeReference(node);
+ default:
+ var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined);
+ ts.setEmitFlags(visited, 1 /* SingleLine */);
+ return visited;
+ }
+ }
+ function transformJSDocOptionalType(node) {
+ return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
+ }
+ function transformJSDocNullableType(node) {
+ return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
+ }
+ function transformJSDocVariadicType(node) {
+ return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
+ }
+ function transformJSDocFunctionType(node) {
+ var parameters = node.parameters && node.parameters.map(transformJSDocType);
+ return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type);
+ }
+ function transformJSDocParameter(node) {
+ var index = node.parent.parameters.indexOf(node);
+ var isRest = node.type.kind === 281 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
+ var name = node.name || (isRest ? "rest" : "arg" + index);
+ var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
+ return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
+ }
+ function transformJSDocTypeReference(node) {
+ var name = node.typeName;
+ var args = node.typeArguments;
+ if (ts.isIdentifier(node.typeName)) {
+ if (ts.isJSDocIndexSignature(node)) {
+ return transformJSDocIndexSignature(node);
+ }
+ var text = node.typeName.text;
+ switch (node.typeName.text) {
+ case "String":
+ case "Boolean":
+ case "Object":
+ case "Number":
+ text = text.toLowerCase();
+ break;
+ case "array":
+ case "date":
+ case "promise":
+ text = text[0].toUpperCase() + text.slice(1);
+ break;
+ }
+ name = ts.createIdentifier(text);
+ if ((text === "Array" || text === "Promise") && !node.typeArguments) {
+ args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
+ }
+ else {
+ args = ts.visitNodes(node.typeArguments, transformJSDocType);
+ }
+ }
+ return ts.createTypeReferenceNode(name, args);
+ }
+ function transformJSDocIndexSignature(node) {
+ var index = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s",
+ /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []),
+ /*initializer*/ undefined);
+ var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
+ ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
+ return indexSignature;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "convertFunctionToEs6Class";
+ var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
+ return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_function_to_an_ES2015_class), changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
+ });
+ function doChange(changes, sourceFile, position, checker) {
+ var deletedNodes = [];
+ var deletes = [];
+ var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false));
+ if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
+ // Bad input
+ return undefined;
+ }
+ var ctorDeclaration = ctorSymbol.valueDeclaration;
+ var precedingNode;
+ var newClassDeclaration;
+ switch (ctorDeclaration.kind) {
+ case 232 /* FunctionDeclaration */:
+ precedingNode = ctorDeclaration;
+ deleteNode(ctorDeclaration);
+ newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
+ break;
+ case 230 /* VariableDeclaration */:
+ precedingNode = ctorDeclaration.parent.parent;
+ if (ctorDeclaration.parent.declarations.length === 1) {
+ deleteNode(precedingNode);
+ }
+ else {
+ deleteNode(ctorDeclaration, /*inList*/ true);
+ }
+ newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
+ break;
+ }
+ if (!newClassDeclaration) {
+ return undefined;
+ }
+ // Because the preceding node could be touched, we need to insert nodes before delete nodes.
+ changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
+ for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) {
+ var deleteCallback = deletes_1[_i];
+ deleteCallback();
+ }
+ function deleteNode(node, inList) {
+ if (inList === void 0) { inList = false; }
+ if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) {
+ // Parent node has already been deleted; do nothing
+ return;
+ }
+ deletedNodes.push(node);
+ if (inList) {
+ deletes.push(function () { return changes.deleteNodeInList(sourceFile, node); });
+ }
+ else {
+ deletes.push(function () { return changes.deleteNode(sourceFile, node); });
+ }
+ }
+ function createClassElementsFromSymbol(symbol) {
+ var memberElements = [];
+ // all instance members are stored in the "member" array of symbol
+ if (symbol.members) {
+ symbol.members.forEach(function (member) {
+ var memberElement = createClassElement(member, /*modifiers*/ undefined);
+ if (memberElement) {
+ memberElements.push(memberElement);
+ }
+ });
+ }
+ // all static members are stored in the "exports" array of symbol
+ if (symbol.exports) {
+ symbol.exports.forEach(function (member) {
+ var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]);
+ if (memberElement) {
+ memberElements.push(memberElement);
+ }
+ });
+ }
+ return memberElements;
+ function shouldConvertDeclaration(_target, source) {
+ // Right now the only thing we can convert are function expressions - other values shouldn't get
+ // transformed. We can update this once ES public class properties are available.
+ return ts.isFunctionLike(source);
+ }
+ function createClassElement(symbol, modifiers) {
+ // both properties and methods are bound as property symbols
+ if (!(symbol.flags & 4 /* Property */)) {
+ return;
+ }
+ var memberDeclaration = symbol.valueDeclaration;
+ var assignmentBinaryExpression = memberDeclaration.parent;
+ if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
+ return;
+ }
+ // 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 === 214 /* ExpressionStatement */
+ ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
+ deleteNode(nodeToDelete);
+ if (!assignmentBinaryExpression.right) {
+ return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
+ /*type*/ undefined, /*initializer*/ undefined);
+ }
+ switch (assignmentBinaryExpression.right.kind) {
+ case 190 /* FunctionExpression */: {
+ var functionExpression = assignmentBinaryExpression.right;
+ var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */));
+ var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
+ /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
+ copyComments(assignmentBinaryExpression, method, sourceFile);
+ return method;
+ }
+ case 191 /* ArrowFunction */: {
+ var arrowFunction = assignmentBinaryExpression.right;
+ var arrowFunctionBody = arrowFunction.body;
+ var bodyBlock = void 0;
+ // case 1: () => { return [1,2,3] }
+ if (arrowFunctionBody.kind === 211 /* Block */) {
+ bodyBlock = arrowFunctionBody;
+ }
+ // case 2: () => [1,2,3]
+ else {
+ bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
+ }
+ var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */));
+ var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
+ /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
+ copyComments(assignmentBinaryExpression, method, sourceFile);
+ return method;
+ }
+ default: {
+ // Don't try to declare members in JavaScript files
+ if (ts.isSourceFileJavaScript(sourceFile)) {
+ return;
+ }
+ var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
+ /*type*/ undefined, assignmentBinaryExpression.right);
+ copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ return prop;
+ }
+ }
+ }
+ }
+ function createClassFromVariableDeclaration(node) {
+ var initializer = node.initializer;
+ if (!initializer || initializer.kind !== 190 /* FunctionExpression */) {
+ return undefined;
+ }
+ if (node.name.kind !== 71 /* Identifier */) {
+ return undefined;
+ }
+ var memberElements = createClassElementsFromSymbol(initializer.symbol);
+ if (initializer.body) {
+ memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
+ }
+ var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */);
+ var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
+ /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
+ // Don't call copyComments here because we'll already leave them in place
+ return cls;
+ }
+ function createClassFromFunctionDeclaration(node) {
+ var memberElements = createClassElementsFromSymbol(ctorSymbol);
+ if (node.body) {
+ memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
+ }
+ var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */);
+ var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
+ /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
+ // Don't call copyComments here because we'll already leave them in place
+ return cls;
+ }
+ }
+ function copyComments(sourceNode, targetNode, sourceFile) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ if (kind === 3 /* MultiLineCommentTrivia */) {
+ // Remove leading /*
+ pos += 2;
+ // Remove trailing */
+ end -= 2;
+ }
+ else {
+ // Remove leading //
+ pos += 2;
+ }
+ ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl);
+ });
+ }
+ function getModifierKindFromSource(source, kind) {
+ return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code],
+ getCodeActions: function (context) {
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module);
+ var sourceFile = context.sourceFile, program = context.program;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
+ var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target);
+ if (moduleExportsChangedToDefault) {
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var importingFile = _a[_i];
+ fixImportOfModuleExports(importingFile, sourceFile, changes);
+ }
+ }
+ });
+ // No support for fix-all since this applies to the whole file at once anyway.
+ return [{ description: description, changes: changes, fixId: undefined }];
+ },
+ });
+ function fixImportOfModuleExports(importingFile, exportingFile, changes) {
+ for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
+ var moduleSpecifier = _a[_i];
+ var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
+ if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
+ continue;
+ }
+ var parent = moduleSpecifier.parent;
+ switch (parent.kind) {
+ case 252 /* ExternalModuleReference */: {
+ var importEq = parent.parent;
+ changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text));
+ break;
+ }
+ case 185 /* CallExpression */: {
+ var call = parent;
+ if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) {
+ changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default"));
+ }
+ break;
+ }
+ }
+ }
+ }
+ /** @returns Whether we converted a `module.exports =` to a default export. */
+ function convertFileToEs6Module(sourceFile, checker, changes, target) {
+ var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
+ var exports = collectExportRenames(sourceFile, checker, identifiers);
+ convertExportsAccesses(sourceFile, exports, changes);
+ var moduleExportsChangedToDefault = false;
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports);
+ moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
+ }
+ return moduleExportsChangedToDefault;
+ }
+ function collectExportRenames(sourceFile, checker, identifiers) {
+ var res = ts.createMap();
+ forEachExportReference(sourceFile, function (node) {
+ var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
+ if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
+ || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) {
+ // Unconditionally add an underscore in case `text` is a keyword.
+ res.set(text, makeUniqueName("_" + text, identifiers));
+ }
+ });
+ return res;
+ }
+ function convertExportsAccesses(sourceFile, exports, changes) {
+ forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
+ if (isAssignmentLhs) {
+ return;
+ }
+ var text = node.name.text;
+ changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
+ });
+ }
+ function forEachExportReference(sourceFile, cb) {
+ sourceFile.forEachChild(function recur(node) {
+ if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
+ var parent = node.parent;
+ cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */);
+ }
+ node.forEachChild(recur);
+ });
+ }
+ function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) {
+ switch (statement.kind) {
+ case 212 /* VariableStatement */:
+ convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target);
+ return false;
+ case 214 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ switch (expression.kind) {
+ case 185 /* CallExpression */: {
+ if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) {
+ // For side-effecting require() call, just make a side-effecting import.
+ changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text));
+ }
+ return false;
+ }
+ case 198 /* BinaryExpression */: {
+ var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
+ return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports);
+ }
+ }
+ }
+ // falls through
+ default:
+ return false;
+ }
+ }
+ function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) {
+ var declarationList = statement.declarationList;
+ var foundImport = false;
+ var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
+ var name = decl.name, initializer = decl.initializer;
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
+ // `const alias = module.exports;` can be removed.
+ foundImport = true;
+ return [];
+ }
+ if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) {
+ foundImport = true;
+ return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target);
+ }
+ else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) {
+ foundImport = true;
+ return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers);
+ }
+ else {
+ // Move it out to its own variable statement.
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
+ }
+ });
+ if (foundImport) {
+ // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ }
+ }
+ /** Converts `const name = require("moduleSpecifier").propertyName` */
+ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) {
+ switch (name.kind) {
+ case 178 /* ObjectBindingPattern */:
+ case 179 /* ArrayBindingPattern */: {
+ // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
+ var tmp = makeUniqueName(propertyName, identifiers);
+ return [
+ makeSingleImport(tmp, propertyName, moduleSpecifier),
+ makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
+ ];
+ }
+ case 71 /* Identifier */:
+ // `const a = require("b").c` --> `import { c as a } from "./b";
+ return [makeSingleImport(name.text, propertyName, moduleSpecifier)];
+ default:
+ ts.Debug.assertNever(name);
+ }
+ }
+ function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) {
+ if (!ts.isPropertyAccessExpression(left)) {
+ return false;
+ }
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
+ // `const alias = module.exports;` or `module.exports = alias;` can be removed.
+ changes.deleteNode(sourceFile, statement);
+ }
+ else {
+ var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
+ var changedToDefaultExport = false;
+ if (!newNodes) {
+ (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ }
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ return changedToDefaultExport;
+ }
+ }
+ else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
+ convertNamedExport(sourceFile, statement, left.name, right, changes, exports);
+ }
+ return false;
+ var _a;
+ }
+ /**
+ * Convert `module.exports = { ... }` to individual exports..
+ * We can't always do this if the module has interesting members -- then it will be a default export instead.
+ */
+ function tryChangeModuleExportsObject(object) {
+ return ts.mapAllOrFail(object.properties, function (prop) {
+ switch (prop.kind) {
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
+ case 269 /* ShorthandPropertyAssignment */:
+ case 270 /* SpreadAssignment */:
+ return undefined;
+ case 268 /* PropertyAssignment */:
+ return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer);
+ case 153 /* MethodDeclaration */:
+ return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop);
+ default:
+ ts.Debug.assertNever(prop);
+ }
+ });
+ }
+ function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) {
+ // If "originalKeywordKind" was set, this is e.g. `exports.
+ var text = propertyName.text;
+ var rename = exports.get(text);
+ if (rename !== undefined) {
+ /*
+ const _class = 0;
+ export { _class as class };
+ */
+ var newNodes = [
+ makeConst(/*modifiers*/ undefined, rename, right),
+ makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
+ ];
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ }
+ else {
+ changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true });
+ }
+ }
+ function convertModuleExportsToExportDefault(exported, checker) {
+ var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
+ switch (exported.kind) {
+ case 190 /* FunctionExpression */:
+ case 191 /* ArrowFunction */: {
+ // `module.exports = function f() {}` --> `export default function f() {}`
+ var fn = exported;
+ return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
+ }
+ case 203 /* ClassExpression */: {
+ // `module.exports = class C {}` --> `export default class C {}`
+ var cls = exported;
+ return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
+ }
+ case 185 /* CallExpression */:
+ if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) {
+ return convertReExportAll(exported.arguments[0], checker);
+ }
+ // falls through
+ default:
+ // `module.exports = 0;` --> `export default 0;`
+ return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
+ }
+ }
+ function convertReExportAll(reExported, checker) {
+ // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
+ var moduleSpecifier = reExported.text;
+ var moduleSymbol = checker.getSymbolAtLocation(reExported);
+ var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
+ return exports.has("export=")
+ ? [[reExportDefault(moduleSpecifier)], true]
+ : !exports.has("default")
+ ? [[reExportStar(moduleSpecifier)], false]
+ // If there's some non-default export, must include both `export *` and `export default`.
+ : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
+ }
+ function reExportStar(moduleSpecifier) {
+ return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
+ }
+ function reExportDefault(moduleSpecifier) {
+ return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
+ }
+ function convertExportsDotXEquals(name, exported) {
+ var modifiers = [ts.createToken(84 /* ExportKeyword */)];
+ switch (exported.kind) {
+ case 190 /* FunctionExpression */: {
+ var expressionName = exported.name;
+ if (expressionName && expressionName.text !== name) {
+ // `exports.f = function g() {}` -> `export const f = function g() {}`
+ return exportConst();
+ }
+ }
+ // falls through
+ case 191 /* ArrowFunction */:
+ // `exports.f = function() {}` --> `export function f() {}`
+ return functionExpressionToDeclaration(name, modifiers, exported);
+ case 203 /* ClassExpression */:
+ // `exports.C = class {}` --> `export class C {}`
+ return classExpressionToDeclaration(name, modifiers, exported);
+ default:
+ return exportConst();
+ }
+ function exportConst() {
+ // `exports.x = 0;` --> `export const x = 0;`
+ return makeConst(modifiers, ts.createIdentifier(name), exported);
+ }
+ }
+ /**
+ * Converts `const <> = require("x");`.
+ * Returns nodes that will replace the variable declaration for the commonjs import.
+ * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
+ */
+ function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) {
+ switch (name.kind) {
+ case 178 /* 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
+ : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
+ });
+ if (importSpecifiers) {
+ return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
+ }
+ }
+ // falls through -- object destructuring has an interesting pattern and must be a variable declaration
+ case 179 /* ArrayBindingPattern */: {
+ /*
+ import x from "x";
+ const [a, b, c] = x;
+ */
+ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers);
+ return [
+ makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
+ makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
+ ];
+ }
+ case 71 /* Identifier */:
+ return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers);
+ default:
+ ts.Debug.assertNever(name);
+ }
+ }
+ /**
+ * Convert `import x = require("x").`
+ * Also converts uses like `x.y()` to `y()` and uses a named import.
+ */
+ function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) {
+ var nameSymbol = checker.getSymbolAtLocation(name);
+ // Maps from module property name to name actually used. (The same if there isn't shadowing.)
+ var namedBindingsNames = ts.createMap();
+ // True if there is some non-property use like `x()` or `f(x)`.
+ var needDefaultImport = false;
+ for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
+ var use = _a[_i];
+ if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
+ // This was a use of a different symbol with the same name, due to shadowing. Ignore.
+ continue;
+ }
+ var parent = use.parent;
+ if (ts.isPropertyAccessExpression(parent)) {
+ var expression = parent.expression, propertyName = parent.name.text;
+ ts.Debug.assert(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);
+ }
+ changes.replaceNode(file, parent, ts.createIdentifier(idName));
+ }
+ else {
+ needDefaultImport = true;
+ }
+ }
+ var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
+ var propertyName = _a[0], idName = _a[1];
+ return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
+ }));
+ if (!namedBindings) {
+ // If it was unused, ensure that we at least import *something*.
+ needDefaultImport = true;
+ }
+ return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ }
+ // Identifiers helpers
+ function makeUniqueName(name, identifiers) {
+ while (identifiers.original.has(name) || identifiers.additional.has(name)) {
+ name = "_" + name;
+ }
+ identifiers.additional.set(name, true);
+ return name;
+ }
+ function collectFreeIdentifiers(file) {
+ var map = ts.createMultiMap();
+ file.forEachChild(function recur(node) {
+ if (ts.isIdentifier(node) && isFreeIdentifier(node)) {
+ map.add(node.text, node);
+ }
+ node.forEachChild(recur);
+ });
+ return map;
+ }
+ function isFreeIdentifier(node) {
+ var parent = node.parent;
+ switch (parent.kind) {
+ case 183 /* PropertyAccessExpression */:
+ return parent.name !== node;
+ case 180 /* BindingElement */:
+ return parent.propertyName !== node;
+ default:
+ return true;
+ }
+ }
+ // Node helpers
+ function functionExpressionToDeclaration(name, additionalModifiers, fn) {
+ return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
+ ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
+ }
+ function classExpressionToDeclaration(name, additionalModifiers, cls) {
+ return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
+ ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
+ }
+ function makeSingleImport(localName, propertyName, moduleSpecifier) {
+ return propertyName === "default"
+ ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
+ : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ }
+ function makeImport(name, namedImports, moduleSpecifier) {
+ return makeImportDeclaration(name, namedImports, ts.createLiteral(moduleSpecifier));
+ }
+ function makeImportDeclaration(name, namedImports, moduleSpecifier) {
+ var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
+ return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier);
+ }
+ codefix.makeImportDeclaration = makeImportDeclaration;
+ function makeImportSpecifier(propertyName, name) {
+ return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
+ }
+ function makeConst(modifiers, name, init) {
+ return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
+ }
+ function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
+ return ts.createExportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -94197,9 +95415,7 @@ var ts;
},
});
function getClass(sourceFile, pos) {
- var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false));
- ts.Debug.assert(!!classDeclaration);
- return classDeclaration;
+ return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)));
}
function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) {
// Note that this is ultimately derived from a map indexed by symbol names,
@@ -94507,7 +95723,6 @@ var ts;
commands: [getCommand(fileName, packageName)],
};
}
- codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes;
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
@@ -94530,17 +95745,21 @@ var ts;
return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }];
},
fixIds: [fixId],
- getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
- addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes);
- }); },
+ getAllCodeActions: function (context) {
+ var seenClassDeclarations = ts.createMap();
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var classDeclaration = getClass(diag.file, diag.start);
+ if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
+ addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes);
+ }
+ });
+ },
});
function getClass(sourceFile, pos) {
- // This is the identifier in the case of a class declaration
+ // Token is the identifier in the case of a class declaration
// or the class keyword token in the case of a class expression.
var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
- var classDeclaration = token.parent;
- ts.Debug.assert(ts.isClassLike(classDeclaration));
- return classDeclaration;
+ return ts.cast(token.parent, ts.isClassLike);
}
function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) {
var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration);
@@ -94880,9 +96099,9 @@ var ts;
changes.deleteNodeInList(sourceFile, parent);
}
break;
- case 243 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *'
+ case 243 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *'
var importClause = parent;
- if (!importClause.namedBindings) {
+ if (!importClause.namedBindings) { // |import d from './file'|
changes.deleteNode(sourceFile, ts.getAncestor(importClause, 242 /* ImportDeclaration */));
}
else {
@@ -95248,7 +96467,7 @@ var ts;
case 252 /* ExternalModuleReference */:
return parent.parent;
case 248 /* ExportDeclaration */:
- case 185 /* CallExpression */:// For "require()" calls
+ case 185 /* CallExpression */: // For "require()" calls
// Ignore these, can't add imports to them.
return undefined;
default:
@@ -95667,7 +96886,7 @@ var ts;
var parent = token.parent;
var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent);
if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258 /* JsxOpeningFragment */) {
- umdSymbol = checker.resolveName(checker.getJsxNamespace(), isNodeOpeningLikeElement ? parent.tagName : parent, 107455 /* Value */, /*excludeGlobals*/ false);
+ umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 107455 /* Value */, /*excludeGlobals*/ false);
}
}
if (ts.isUMDExportSymbol(umdSymbol)) {
@@ -95697,7 +96916,7 @@ var ts;
// Fall back to the `import * as ns` style import.
return 2 /* Namespace */;
default:
- throw ts.Debug.assertNever(moduleKind);
+ return ts.Debug.assertNever(moduleKind);
}
}
function getActionsForNonUMDImport(context) {
@@ -96167,7 +97386,7 @@ var ts;
case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, program, cancellationToken) : undefined;
default:
- throw ts.Debug.fail(String(errorCode));
+ return ts.Debug.fail(String(errorCode));
}
}
function isAllowedTokenKind(kind) {
@@ -96337,13 +97556,13 @@ var ts;
var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
return callContexts && declaration.parameters.map(function (parameter, parameterIndex) {
var types = [];
- var isRestParameter = ts.isRestParameter(parameter);
+ var isRest = ts.isRestParameter(parameter);
for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) {
var callContext = callContexts_1[_i];
if (callContext.argumentTypes.length <= parameterIndex) {
continue;
}
- if (isRestParameter) {
+ if (isRest) {
for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) {
types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i]));
}
@@ -96356,7 +97575,7 @@ var ts;
return undefined;
}
var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */));
- return isRestParameter ? checker.createArrayType(type) : type;
+ return isRest ? checker.createArrayType(type) : type;
});
}
InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences;
@@ -96413,6 +97632,8 @@ var ts;
case 37 /* PlusToken */:
usageContext.isNumberOrString = true;
break;
+ // case SyntaxKind.ExclamationToken:
+ // no inferences here;
}
}
function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) {
@@ -96678,9 +97899,7 @@ var ts;
var opts = context.program.getCompilerOptions();
var variations = [];
// import Bluebird from "bluebird";
- variations.push(createAction(context, sourceFile, node, ts.createImportDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
@@ -96729,7 +97948,171 @@ var ts;
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
+ var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
+ var fixIdAddInitializer = "addMissingPropertyInitializer";
+ var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start);
+ if (!propertyDeclaration)
+ return;
+ var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
+ var result = [
+ getActionForAddMissingUndefinedType(context, propertyDeclaration),
+ getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter)
+ ];
+ ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter));
+ return result;
+ },
+ fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
+ getAllCodeActions: function (context) {
+ var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start);
+ if (!propertyDeclaration)
+ return;
+ switch (context.fixId) {
+ case fixIdAddDefiniteAssignmentAssertions:
+ addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration, newLineCharacter);
+ break;
+ case fixIdAddUndefinedType:
+ addUndefinedType(changes, diag.file, propertyDeclaration);
+ break;
+ case fixIdAddInitializer:
+ var checker = context.program.getTypeChecker();
+ var initializer = getInitializer(checker, propertyDeclaration);
+ if (!initializer)
+ return;
+ addInitializer(changes, diag.file, propertyDeclaration, initializer, newLineCharacter);
+ break;
+ default:
+ ts.Debug.fail(JSON.stringify(context.fixId));
+ }
+ });
+ },
+ });
+ function getPropertyDeclaration(sourceFile, pos) {
+ var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined;
+ }
+ function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter) {
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_definite_assignment_assertion_to_property_0), [propertyDeclaration.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration, newLineCharacter); });
+ return { description: description, changes: changes, fixId: fixIdAddDefiniteAssignmentAssertions };
+ }
+ function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, newLineCharacter) {
+ var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer);
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter });
+ }
+ function getActionForAddMissingUndefinedType(context, propertyDeclaration) {
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_undefined_type_to_property_0), [propertyDeclaration.name.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); });
+ return { description: description, changes: changes, fixId: fixIdAddUndefinedType };
+ }
+ function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
+ var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */);
+ var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode];
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types));
+ }
+ function getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter) {
+ var checker = context.program.getTypeChecker();
+ var initializer = getInitializer(checker, propertyDeclaration);
+ if (!initializer)
+ return undefined;
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_initializer_to_property_0), [propertyDeclaration.name.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer, newLineCharacter); });
+ return { description: description, changes: changes, fixId: fixIdAddInitializer };
+ }
+ function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer, newLineCharacter) {
+ var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer);
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter });
+ }
+ function getInitializer(checker, propertyDeclaration) {
+ return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type));
+ }
+ function getDefaultValueFromType(checker, type) {
+ if (type.flags & 2 /* String */) {
+ return ts.createLiteral("");
+ }
+ else if (type.flags & 4 /* Number */) {
+ return ts.createNumericLiteral("0");
+ }
+ else if (type.flags & 8 /* Boolean */) {
+ return ts.createFalse();
+ }
+ else if (type.flags & 224 /* Literal */) {
+ return ts.createLiteral(type.value);
+ }
+ else if (type.flags & 131072 /* Union */) {
+ return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); });
+ }
+ else if (ts.getObjectFlags(type) & 1 /* Class */) {
+ var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
+ if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */))
+ return undefined;
+ var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; });
+ if (constructorDeclaration && constructorDeclaration.parameters.length)
+ return undefined;
+ return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
+ }
+ return undefined;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "useDefaultImport";
+ var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, start = context.span.start;
+ var info = getInfo(sourceFile, start);
+ if (!info)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
+ return [{ description: description, changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var info = getInfo(diag.file, diag.start);
+ if (info)
+ doChange(changes, diag.file, info);
+ }); },
+ });
+ function getInfo(sourceFile, pos) {
+ var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ if (!ts.isIdentifier(name))
+ return undefined; // bad input
+ var parent = name.parent;
+ if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) {
+ return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression };
+ }
+ else if (ts.isNamespaceImport(parent)) {
+ var importNode = parent.parent.parent;
+ return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier };
+ }
+ }
+ function doChange(changes, sourceFile, info) {
+ changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
///
+///
+///
+///
///
///
///
@@ -96748,960 +98131,8 @@ var ts;
///
///
///
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var annotateWithTypeFromJSDoc;
- (function (annotateWithTypeFromJSDoc) {
- var refactorName = "Annotate with type from JSDoc";
- var actionName = "annotate";
- var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (ts.isInJavaScriptFile(context.file)) {
- return undefined;
- }
- var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false);
- if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) {
- return [{
- name: refactorName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName
- }
- ]
- }];
- }
- }
- function hasUsableJSDoc(decl) {
- if (!decl) {
- return false;
- }
- if (ts.isFunctionLikeDeclaration(decl)) {
- return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl));
- }
- return !decl.type && !!ts.getJSDocType(decl);
- }
- function getEditsForAction(context, action) {
- if (actionName !== action) {
- return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action);
- }
- var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false);
- var decl = ts.findAncestor(node, isDeclarationWithType);
- if (!decl || decl.type) {
- return undefined;
- }
- var jsdocType = ts.getJSDocType(decl);
- var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }));
- if (isFunctionWithJSDoc || jsdocType && decl.kind === 148 /* Parameter */) {
- return getEditsForFunctionAnnotation(context);
- }
- else if (jsdocType) {
- return getEditsForAnnotation(context);
- }
- else {
- ts.Debug.assert(!!refactor, "No applicable refactor found.");
- }
- }
- function getEditsForAnnotation(context) {
- var sourceFile = context.file;
- var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false);
- var decl = ts.findAncestor(token, isDeclarationWithType);
- var jsdocType = ts.getJSDocType(decl);
- if (!decl || !jsdocType || decl.type) {
- return ts.Debug.fail("!decl || !jsdocType || decl.type: !" + decl + " || !" + jsdocType + " || " + decl.type);
- }
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var declarationWithType = addType(decl, transformJSDocType(jsdocType));
- ts.suppressLeadingAndTrailingTrivia(declarationWithType);
- changeTracker.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions);
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined
- };
- }
- function getEditsForFunctionAnnotation(context) {
- var sourceFile = context.file;
- var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false);
- var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration);
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var functionWithType = addTypesToFunctionLike(decl);
- ts.suppressLeadingAndTrailingTrivia(functionWithType);
- changeTracker.replaceNode(sourceFile, decl, functionWithType, ts.textChanges.useNonAdjustedPositions);
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined
- };
- }
- function isDeclarationWithType(node) {
- return ts.isFunctionLikeDeclaration(node) ||
- node.kind === 230 /* VariableDeclaration */ ||
- node.kind === 148 /* Parameter */ ||
- node.kind === 150 /* PropertySignature */ ||
- node.kind === 151 /* PropertyDeclaration */;
- }
- function addTypesToFunctionLike(decl) {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, /*checkJSDoc*/ true);
- var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, /*checkJSDoc*/ true)), p.initializer); });
- var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, /*checkJSDoc*/ true));
- switch (decl.kind) {
- case 232 /* FunctionDeclaration */:
- return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
- case 154 /* Constructor */:
- return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body);
- case 190 /* FunctionExpression */:
- return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
- case 191 /* ArrowFunction */:
- return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body);
- case 153 /* MethodDeclaration */:
- return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body);
- case 155 /* GetAccessor */:
- return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body);
- case 156 /* SetAccessor */:
- return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body);
- default:
- return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind);
- }
- }
- function addType(decl, jsdocType) {
- switch (decl.kind) {
- case 230 /* VariableDeclaration */:
- return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer);
- case 150 /* PropertySignature */:
- return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
- case 151 /* PropertyDeclaration */:
- return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
- default:
- return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind);
- }
- }
- function transformJSDocType(node) {
- if (node === undefined) {
- return undefined;
- }
- switch (node.kind) {
- case 275 /* JSDocAllType */:
- case 276 /* JSDocUnknownType */:
- return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 279 /* JSDocOptionalType */:
- return transformJSDocOptionalType(node);
- case 278 /* JSDocNonNullableType */:
- return transformJSDocType(node.type);
- case 277 /* JSDocNullableType */:
- return transformJSDocNullableType(node);
- case 281 /* JSDocVariadicType */:
- return transformJSDocVariadicType(node);
- case 280 /* JSDocFunctionType */:
- return transformJSDocFunctionType(node);
- case 148 /* Parameter */:
- return transformJSDocParameter(node);
- case 161 /* TypeReference */:
- return transformJSDocTypeReference(node);
- default:
- var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined);
- ts.setEmitFlags(visited, 1 /* SingleLine */);
- return visited;
- }
- }
- function transformJSDocOptionalType(node) {
- return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
- }
- function transformJSDocNullableType(node) {
- return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
- }
- function transformJSDocVariadicType(node) {
- return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
- }
- function transformJSDocFunctionType(node) {
- var parameters = node.parameters && node.parameters.map(transformJSDocType);
- return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type);
- }
- function transformJSDocParameter(node) {
- var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 281 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
- var name = node.name || (isRest ? "rest" : "arg" + index);
- var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
- return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
- }
- function transformJSDocTypeReference(node) {
- var name = node.typeName;
- var args = node.typeArguments;
- if (ts.isIdentifier(node.typeName)) {
- if (ts.isJSDocIndexSignature(node)) {
- return transformJSDocIndexSignature(node);
- }
- var text = node.typeName.text;
- switch (node.typeName.text) {
- case "String":
- case "Boolean":
- case "Object":
- case "Number":
- text = text.toLowerCase();
- break;
- case "array":
- case "date":
- case "promise":
- text = text[0].toUpperCase() + text.slice(1);
- break;
- }
- name = ts.createIdentifier(text);
- if ((text === "Array" || text === "Promise") && !node.typeArguments) {
- args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
- }
- else {
- args = ts.visitNodes(node.typeArguments, transformJSDocType);
- }
- }
- return ts.createTypeReferenceNode(name, args);
- }
- function transformJSDocIndexSignature(node) {
- var index = ts.createParameter(
- /*decorators*/ undefined,
- /*modifiers*/ undefined,
- /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s",
- /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []),
- /*initializer*/ undefined);
- var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
- ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
- return indexSignature;
- }
- })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var convertFunctionToES6Class;
- (function (convertFunctionToES6Class) {
- var refactorName = "Convert to ES2015 class";
- var actionName = "convert";
- var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (!ts.isInJavaScriptFile(context.file)) {
- return undefined;
- }
- var symbol = getConstructorSymbol(context);
- if (!symbol) {
- return undefined;
- }
- if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) {
- symbol = symbol.valueDeclaration.initializer.symbol;
- }
- if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) {
- return [
- {
- name: refactorName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName
- }
- ]
- }
- ];
- }
- }
- function getEditsForAction(context, action) {
- // Somehow wrong action got invoked?
- if (actionName !== action) {
- return undefined;
- }
- var sourceFile = context.file;
- var ctorSymbol = getConstructorSymbol(context);
- var deletedNodes = [];
- var deletes = [];
- if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
- return undefined;
- }
- var ctorDeclaration = ctorSymbol.valueDeclaration;
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var precedingNode;
- var newClassDeclaration;
- switch (ctorDeclaration.kind) {
- case 232 /* FunctionDeclaration */:
- precedingNode = ctorDeclaration;
- deleteNode(ctorDeclaration);
- newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
- break;
- case 230 /* VariableDeclaration */:
- precedingNode = ctorDeclaration.parent.parent;
- if (ctorDeclaration.parent.declarations.length === 1) {
- deleteNode(precedingNode);
- }
- else {
- deleteNode(ctorDeclaration, /*inList*/ true);
- }
- newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
- break;
- }
- if (!newClassDeclaration) {
- return undefined;
- }
- // Because the preceding node could be touched, we need to insert nodes before delete nodes.
- changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
- for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) {
- var deleteCallback = deletes_1[_i];
- deleteCallback();
- }
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined,
- };
- function deleteNode(node, inList) {
- if (inList === void 0) { inList = false; }
- if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) {
- // Parent node has already been deleted; do nothing
- return;
- }
- deletedNodes.push(node);
- if (inList) {
- deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); });
- }
- else {
- deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); });
- }
- }
- function createClassElementsFromSymbol(symbol) {
- var memberElements = [];
- // all instance members are stored in the "member" array of symbol
- if (symbol.members) {
- symbol.members.forEach(function (member) {
- var memberElement = createClassElement(member, /*modifiers*/ undefined);
- if (memberElement) {
- memberElements.push(memberElement);
- }
- });
- }
- // all static members are stored in the "exports" array of symbol
- if (symbol.exports) {
- symbol.exports.forEach(function (member) {
- var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]);
- if (memberElement) {
- memberElements.push(memberElement);
- }
- });
- }
- return memberElements;
- function shouldConvertDeclaration(_target, source) {
- // Right now the only thing we can convert are function expressions - other values shouldn't get
- // transformed. We can update this once ES public class properties are available.
- return ts.isFunctionLike(source);
- }
- function createClassElement(symbol, modifiers) {
- // both properties and methods are bound as property symbols
- if (!(symbol.flags & 4 /* Property */)) {
- return;
- }
- var memberDeclaration = symbol.valueDeclaration;
- var assignmentBinaryExpression = memberDeclaration.parent;
- if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
- return;
- }
- // 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 === 214 /* ExpressionStatement */
- ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
- deleteNode(nodeToDelete);
- if (!assignmentBinaryExpression.right) {
- return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
- /*type*/ undefined, /*initializer*/ undefined);
- }
- switch (assignmentBinaryExpression.right.kind) {
- case 190 /* FunctionExpression */: {
- var functionExpression = assignmentBinaryExpression.right;
- var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */));
- var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
- /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- copyComments(assignmentBinaryExpression, method);
- return method;
- }
- case 191 /* ArrowFunction */: {
- var arrowFunction = assignmentBinaryExpression.right;
- var arrowFunctionBody = arrowFunction.body;
- var bodyBlock = void 0;
- // case 1: () => { return [1,2,3] }
- if (arrowFunctionBody.kind === 211 /* Block */) {
- bodyBlock = arrowFunctionBody;
- }
- else {
- bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
- }
- var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */));
- var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
- /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- copyComments(assignmentBinaryExpression, method);
- return method;
- }
- default: {
- // Don't try to declare members in JavaScript files
- if (ts.isSourceFileJavaScript(sourceFile)) {
- return;
- }
- var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
- /*type*/ undefined, assignmentBinaryExpression.right);
- copyComments(assignmentBinaryExpression.parent, prop);
- return prop;
- }
- }
- }
- }
- function copyComments(sourceNode, targetNode) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
- if (kind === 3 /* MultiLineCommentTrivia */) {
- // Remove leading /*
- pos += 2;
- // Remove trailing */
- end -= 2;
- }
- else {
- // Remove leading //
- pos += 2;
- }
- ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl);
- });
- }
- function createClassFromVariableDeclaration(node) {
- var initializer = node.initializer;
- if (!initializer || initializer.kind !== 190 /* FunctionExpression */) {
- return undefined;
- }
- if (node.name.kind !== 71 /* Identifier */) {
- return undefined;
- }
- var memberElements = createClassElementsFromSymbol(initializer.symbol);
- if (initializer.body) {
- memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
- }
- var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */);
- var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
- /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
- // Don't call copyComments here because we'll already leave them in place
- return cls;
- }
- function createClassFromFunctionDeclaration(node) {
- var memberElements = createClassElementsFromSymbol(ctorSymbol);
- if (node.body) {
- memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
- }
- var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */);
- var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
- /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
- // Don't call copyComments here because we'll already leave them in place
- return cls;
- }
- function getModifierKindFromSource(source, kind) {
- return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
- }
- }
- function getConstructorSymbol(_a) {
- var startPosition = _a.startPosition, file = _a.file, program = _a.program;
- var checker = program.getTypeChecker();
- var token = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- return checker.getSymbolAtLocation(token);
- }
- })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var actionName = "Convert to ES6 module";
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module);
- refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- var file = context.file, startPosition = context.startPosition;
- if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) {
- return undefined;
- }
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- return !isAtTriggerLocation(file, node) ? undefined : [
- {
- name: actionName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function isAtTriggerLocation(sourceFile, node, onSecondTry) {
- if (onSecondTry === void 0) { onSecondTry = false; }
- switch (node.kind) {
- case 185 /* CallExpression */:
- return isAtTopLevelRequire(node);
- case 183 /* PropertyAccessExpression */:
- return ts.isExportsOrModuleExportsOrAlias(sourceFile, node)
- || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression);
- case 231 /* VariableDeclarationList */:
- return isVariableDeclarationTriggerLocation(ts.firstOrUndefined(node.declarations));
- case 230 /* VariableDeclaration */:
- return isVariableDeclarationTriggerLocation(node);
- default:
- return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node)
- || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true);
- }
- function isVariableDeclarationTriggerLocation(decl) {
- return !!decl && !!decl.initializer && ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer);
- }
- }
- function isAtTopLevelRequire(call) {
- if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) {
- return false;
- }
- var propAccess = call.parent;
- var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess;
- if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) {
- return true;
- }
- if (!ts.isVariableDeclaration(varDecl)) {
- return false;
- }
- var varDeclList = varDecl.parent;
- if (varDeclList.kind !== 231 /* VariableDeclarationList */) {
- return false;
- }
- var varStatement = varDeclList.parent;
- return varStatement.kind === 212 /* VariableStatement */ && varStatement.parent.kind === 272 /* SourceFile */;
- }
- function getEditsForAction(context, _actionName) {
- ts.Debug.assertEqual(actionName, _actionName);
- var file = context.file, program = context.program;
- ts.Debug.assert(ts.isSourceFileJavaScript(file));
- var edits = ts.textChanges.ChangeTracker.with(context, function (changes) {
- var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target);
- if (moduleExportsChangedToDefault) {
- for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
- var importingFile = _a[_i];
- fixImportOfModuleExports(importingFile, file, changes);
- }
- }
- });
- return { edits: edits, renameFilename: undefined, renameLocation: undefined };
- }
- function fixImportOfModuleExports(importingFile, exportingFile, changes) {
- for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
- var moduleSpecifier = _a[_i];
- var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
- if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
- continue;
- }
- var parent = moduleSpecifier.parent;
- switch (parent.kind) {
- case 252 /* ExternalModuleReference */: {
- var importEq = parent.parent;
- changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text));
- break;
- }
- case 185 /* CallExpression */: {
- var call = parent;
- if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) {
- changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default"));
- }
- break;
- }
- }
- }
- }
- /** @returns Whether we converted a `module.exports =` to a default export. */
- function convertFileToEs6Module(sourceFile, checker, changes, target) {
- var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
- var exports = collectExportRenames(sourceFile, checker, identifiers);
- convertExportsAccesses(sourceFile, exports, changes);
- var moduleExportsChangedToDefault = false;
- for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
- var statement = _a[_i];
- var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports);
- moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
- }
- return moduleExportsChangedToDefault;
- }
- function collectExportRenames(sourceFile, checker, identifiers) {
- var res = ts.createMap();
- forEachExportReference(sourceFile, function (node) {
- var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
- if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
- || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) {
- // Unconditionally add an underscore in case `text` is a keyword.
- res.set(text, makeUniqueName("_" + text, identifiers));
- }
- });
- return res;
- }
- function convertExportsAccesses(sourceFile, exports, changes) {
- forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
- if (isAssignmentLhs) {
- return;
- }
- var text = node.name.text;
- changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
- });
- }
- function forEachExportReference(sourceFile, cb) {
- sourceFile.forEachChild(function recur(node) {
- if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
- var parent = node.parent;
- cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */);
- }
- node.forEachChild(recur);
- });
- }
- function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) {
- switch (statement.kind) {
- case 212 /* VariableStatement */:
- convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target);
- return false;
- case 214 /* ExpressionStatement */: {
- var expression = statement.expression;
- switch (expression.kind) {
- case 185 /* CallExpression */: {
- if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) {
- // For side-effecting require() call, just make a side-effecting import.
- changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text));
- }
- return false;
- }
- case 198 /* BinaryExpression */: {
- var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
- return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports);
- }
- }
- }
- // falls through
- default:
- return false;
- }
- }
- function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) {
- var declarationList = statement.declarationList;
- var foundImport = false;
- var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
- var name = decl.name, initializer = decl.initializer;
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
- // `const alias = module.exports;` can be removed.
- foundImport = true;
- return [];
- }
- if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) {
- foundImport = true;
- return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target);
- }
- else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) {
- foundImport = true;
- return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers);
- }
- else {
- // Move it out to its own variable statement.
- return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
- }
- });
- if (foundImport) {
- // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- }
- }
- /** Converts `const name = require("moduleSpecifier").propertyName` */
- function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) {
- switch (name.kind) {
- case 178 /* ObjectBindingPattern */:
- case 179 /* ArrayBindingPattern */: {
- // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
- var tmp = makeUniqueName(propertyName, identifiers);
- return [
- makeSingleImport(tmp, propertyName, moduleSpecifier),
- makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
- ];
- }
- case 71 /* Identifier */:
- // `const a = require("b").c` --> `import { c as a } from "./b";
- return [makeSingleImport(name.text, propertyName, moduleSpecifier)];
- default:
- ts.Debug.assertNever(name);
- }
- }
- function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) {
- if (!ts.isPropertyAccessExpression(left)) {
- return false;
- }
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
- // `const alias = module.exports;` or `module.exports = alias;` can be removed.
- changes.deleteNode(sourceFile, statement);
- }
- else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
- }
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- return changedToDefaultExport;
- }
- }
- else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
- convertNamedExport(sourceFile, statement, left.name, right, changes, exports);
- }
- return false;
- var _a;
- }
- /**
- * Convert `module.exports = { ... }` to individual exports..
- * We can't always do this if the module has interesting members -- then it will be a default export instead.
- */
- function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
- switch (prop.kind) {
- case 155 /* GetAccessor */:
- case 156 /* SetAccessor */:
- // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
- case 269 /* ShorthandPropertyAssignment */:
- case 270 /* SpreadAssignment */:
- return undefined;
- case 268 /* PropertyAssignment */:
- return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer);
- case 153 /* MethodDeclaration */:
- return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop);
- default:
- ts.Debug.assertNever(prop);
- }
- });
- }
- function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) {
- // If "originalKeywordKind" was set, this is e.g. `exports.
- var text = propertyName.text;
- var rename = exports.get(text);
- if (rename !== undefined) {
- /*
- const _class = 0;
- export { _class as class };
- */
- var newNodes = [
- makeConst(/*modifiers*/ undefined, rename, right),
- makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
- ];
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- }
- else {
- changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true });
- }
- }
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
- switch (exported.kind) {
- case 190 /* FunctionExpression */:
- case 191 /* ArrowFunction */: {
- // `module.exports = function f() {}` --> `export default function f() {}`
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 203 /* ClassExpression */: {
- // `module.exports = class C {}` --> `export default class C {}`
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 185 /* CallExpression */:
- if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) {
- return convertReExportAll(exported.arguments[0], checker);
- }
- // falls through
- default:
- // `module.exports = 0;` --> `export default 0;`
- return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
- }
- }
- function convertReExportAll(reExported, checker) {
- // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
- var moduleSpecifier = reExported.text;
- var moduleSymbol = checker.getSymbolAtLocation(reExported);
- var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
- return exports.has("export=")
- ? [[reExportDefault(moduleSpecifier)], true]
- : !exports.has("default")
- ? [[reExportStar(moduleSpecifier)], false]
- // If there's some non-default export, must include both `export *` and `export default`.
- : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
- }
- function reExportStar(moduleSpecifier) {
- return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
- }
- function reExportDefault(moduleSpecifier) {
- return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
- }
- function convertExportsDotXEquals(name, exported) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */)];
- switch (exported.kind) {
- case 190 /* FunctionExpression */: {
- var expressionName = exported.name;
- if (expressionName && expressionName.text !== name) {
- // `exports.f = function g() {}` -> `export const f = function g() {}`
- return exportConst();
- }
- }
- // falls through
- case 191 /* ArrowFunction */:
- // `exports.f = function() {}` --> `export function f() {}`
- return functionExpressionToDeclaration(name, modifiers, exported);
- case 203 /* ClassExpression */:
- // `exports.C = class {}` --> `export class C {}`
- return classExpressionToDeclaration(name, modifiers, exported);
- default:
- return exportConst();
- }
- function exportConst() {
- // `exports.x = 0;` --> `export const x = 0;`
- return makeConst(modifiers, ts.createIdentifier(name), exported);
- }
- }
- /**
- * Converts `const <> = require("x");`.
- * Returns nodes that will replace the variable declaration for the commonjs import.
- * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
- */
- function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) {
- switch (name.kind) {
- case 178 /* 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
- : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
- });
- if (importSpecifiers) {
- return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
- }
- }
- // falls through -- object destructuring has an interesting pattern and must be a variable declaration
- case 179 /* ArrayBindingPattern */: {
- /*
- import x from "x";
- const [a, b, c] = x;
- */
- var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers);
- return [
- makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
- makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
- ];
- }
- case 71 /* Identifier */:
- return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers);
- default:
- ts.Debug.assertNever(name);
- }
- }
- /**
- * Convert `import x = require("x").`
- * Also converts uses like `x.y()` to `y()` and uses a named import.
- */
- function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) {
- var nameSymbol = checker.getSymbolAtLocation(name);
- // Maps from module property name to name actually used. (The same if there isn't shadowing.)
- var namedBindingsNames = ts.createMap();
- // True if there is some non-property use like `x()` or `f(x)`.
- var needDefaultImport = false;
- for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
- var use = _a[_i];
- if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
- // This was a use of a different symbol with the same name, due to shadowing. Ignore.
- continue;
- }
- var parent = use.parent;
- if (ts.isPropertyAccessExpression(parent)) {
- var expression = parent.expression, propertyName = parent.name.text;
- ts.Debug.assert(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);
- }
- changes.replaceNode(file, parent, ts.createIdentifier(idName));
- }
- else {
- needDefaultImport = true;
- }
- }
- var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
- var propertyName = _a[0], idName = _a[1];
- return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
- }));
- if (!namedBindings) {
- // If it was unused, ensure that we at least import *something*.
- needDefaultImport = true;
- }
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
- }
- // Identifiers helpers
- function makeUniqueName(name, identifiers) {
- while (identifiers.original.has(name) || identifiers.additional.has(name)) {
- name = "_" + name;
- }
- identifiers.additional.set(name, true);
- return name;
- }
- function collectFreeIdentifiers(file) {
- var map = ts.createMultiMap();
- file.forEachChild(function recur(node) {
- if (ts.isIdentifier(node) && isFreeIdentifier(node)) {
- map.add(node.text, node);
- }
- node.forEachChild(recur);
- });
- return map;
- }
- function isFreeIdentifier(node) {
- var parent = node.parent;
- switch (parent.kind) {
- case 183 /* PropertyAccessExpression */:
- return parent.name !== node;
- case 180 /* BindingElement */:
- return parent.propertyName !== node;
- default:
- return true;
- }
- }
- // Node helpers
- function functionExpressionToDeclaration(name, additionalModifiers, fn) {
- return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
- ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
- }
- function classExpressionToDeclaration(name, additionalModifiers, cls) {
- return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
- ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
- }
- function makeSingleImport(localName, propertyName, moduleSpecifier) {
- return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
- : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
- }
- function makeImport(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier));
- }
- function makeImportSpecifier(propertyName, name) {
- return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
- }
- function makeConst(modifiers, name, init) {
- return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
- }
- function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
- return ts.createExportDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
- }
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
+///
+///
///
///
/* @internal */
@@ -97926,7 +98357,7 @@ var ts;
}
else if (ts.isVariableStatement(node)) {
var numInitializers = 0;
- var lastInitializer = undefined;
+ var lastInitializer = void 0;
for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (declaration.initializer) {
@@ -98043,7 +98474,7 @@ var ts;
switch (node.kind) {
case 232 /* FunctionDeclaration */:
case 233 /* ClassDeclaration */:
- if (node.parent.kind === 272 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) {
+ if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
// You cannot extract global declarations
(errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
}
@@ -98323,12 +98754,12 @@ var ts;
var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text);
var isJS = ts.isInJavaScriptFile(scope);
var functionName = ts.createIdentifier(functionNameText);
- var returnType = undefined;
+ var returnType;
var parameters = [];
var callArguments = [];
var writes;
usagesInScope.forEach(function (usage, name) {
- var typeNode = undefined;
+ var typeNode;
if (!isJS) {
var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
// Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
@@ -98615,7 +99046,7 @@ var ts;
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function getContainingVariableDeclarationIfInList(node, scope) {
- var prevNode = undefined;
+ var prevNode;
while (node !== undefined && node !== scope) {
if (ts.isVariableDeclaration(node) &&
node.initializer === prevNode &&
@@ -98640,16 +99071,16 @@ var ts;
ts.Debug.assert(fileName === renameFilename);
for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) {
var change = textChanges_3[_b];
- var span_15 = change.span, newText = change.newText;
+ var span_14 = change.span, newText = change.newText;
var index = newText.indexOf(functionNameText);
if (index !== -1) {
- lastPos = span_15.start + delta + index;
+ lastPos = span_14.start + delta + index;
// If the reference comes first, return immediately.
if (!isDeclaredBeforeUse) {
return lastPos;
}
}
- delta += newText.length - span_15.length;
+ delta += newText.length - span_14.length;
}
}
// If the declaration comes first, return the position of the last occurrence.
@@ -98658,7 +99089,7 @@ var ts;
return lastPos;
}
function getFirstDeclaration(type) {
- var firstDeclaration = undefined;
+ var firstDeclaration;
var symbol = type.symbol;
if (symbol && symbol.declarations) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
@@ -98780,7 +99211,7 @@ var ts;
function getNodeToInsertPropertyBefore(maxPos, scope) {
var members = scope.members;
ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one.
- var prevMember = undefined;
+ var prevMember;
var allProperties = true;
for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
var member = members_6[_i];
@@ -98802,7 +99233,7 @@ var ts;
}
function getNodeToInsertConstantBefore(node, scope) {
ts.Debug.assert(!ts.isClassLike(scope));
- var prevScope = undefined;
+ var prevScope;
for (var curr = node; curr !== scope; curr = curr.parent) {
if (isScope(curr)) {
prevScope = curr;
@@ -98810,7 +99241,7 @@ var ts;
}
for (var curr = (prevScope || node).parent;; curr = curr.parent) {
if (isBlockLike(curr)) {
- var prevStatement = undefined;
+ var prevStatement = void 0;
for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) {
var statement = _a[_i];
if (statement.pos > node.pos) {
@@ -98875,13 +99306,13 @@ var ts;
var visibleDeclarationsInExtractedRange = [];
var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID
var exposedVariableDeclarations = [];
- var firstExposedNonVariableDeclaration = undefined;
+ var firstExposedNonVariableDeclaration;
var expression = !isReadonlyArray(targetRange.range)
? targetRange.range
: targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0])
? targetRange.range[0].expression
: undefined;
- var expressionDiagnostic = undefined;
+ var expressionDiagnostic;
if (expression === undefined) {
var statements = targetRange.range;
var start = ts.first(statements).getStart();
@@ -98959,7 +99390,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_10 = function (i) {
+ var _loop_11 = 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
@@ -98969,7 +99400,7 @@ var ts;
constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
}
var hasWrite = false;
- var readonlyClassPropertyWrite = undefined;
+ var readonlyClassPropertyWrite;
usagesPerScope[i].usages.forEach(function (value) {
if (value.usage === 2 /* Write */) {
hasWrite = true;
@@ -98999,7 +99430,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_10(i);
+ _loop_11(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function hasTypeParameters(node) {
@@ -99267,165 +99698,7 @@ var ts;
})(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var installTypesForPackage;
- (function (installTypesForPackage) {
- var refactorName = "Install missing types package";
- var actionName = "install";
- var description = "Install missing types package";
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) {
- // Then it will be available via `fixCannotFindModule`.
- return undefined;
- }
- var action = getAction(context);
- return action && [
- {
- name: refactorName,
- description: description,
- actions: [
- {
- description: action.description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function getEditsForAction(context, _actionName) {
- ts.Debug.assertEqual(actionName, _actionName);
- var action = getAction(context); // Should be defined if we said there was an action available.
- return {
- edits: [],
- renameFilename: undefined,
- renameLocation: undefined,
- commands: action.commands,
- };
- }
- function getAction(context) {
- var file = context.file, startPosition = context.startPosition;
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- if (!ts.isStringLiteral(node) || !isModuleIdentifier(node)) {
- return undefined;
- }
- var resolvedTo = ts.getResolvedModule(file, node.text);
- // Still offer to install types if it resolved to e.g. a ".js" file.
- // `tryGetCodeActionForInstallPackageTypes` will verify that we're looking for a valid package name,
- // so the fix won't trigger for imports of ".js" files that couldn't be better replaced by typings.
- if (resolvedTo && ts.extensionIsTypeScript(resolvedTo.extension)) {
- return undefined;
- }
- return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, file.fileName, node.text);
- }
- function isModuleIdentifier(node) {
- switch (node.parent.kind) {
- case 242 /* ImportDeclaration */:
- case 252 /* ExternalModuleReference */:
- return true;
- default:
- return false;
- }
- }
- })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var installTypesForPackage;
- (function (installTypesForPackage) {
- var actionName = "Convert to default import";
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import);
- refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- var file = context.file, startPosition = context.startPosition, program = context.program;
- if (!ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
- return undefined;
- }
- var importInfo = getConvertibleImportAtPosition(file, startPosition);
- if (!importInfo) {
- return undefined;
- }
- var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
- if (!(resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) {
- return undefined;
- }
- return [
- {
- name: actionName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function getEditsForAction(context, _actionName) {
- var file = context.file, startPosition = context.startPosition;
- ts.Debug.assertEqual(actionName, _actionName);
- var importInfo = getConvertibleImportAtPosition(file, startPosition);
- if (!importInfo) {
- return undefined;
- }
- var importStatement = importInfo.importStatement, name = importInfo.name, moduleSpecifier = importInfo.moduleSpecifier;
- var newImportClause = ts.createImportClause(name, /*namedBindings*/ undefined);
- var newImportStatement = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newImportClause, moduleSpecifier);
- return {
- edits: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, importStatement, newImportStatement); }),
- renameFilename: undefined,
- renameLocation: undefined,
- };
- }
- function getConvertibleImportAtPosition(file, startPosition) {
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- while (true) {
- switch (node.kind) {
- case 241 /* ImportEqualsDeclaration */:
- var eq = node;
- var moduleReference = eq.moduleReference;
- return moduleReference.kind === 252 /* ExternalModuleReference */ && ts.isStringLiteral(moduleReference.expression)
- ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression }
- : undefined;
- case 242 /* ImportDeclaration */:
- var d = node;
- var importClause = d.importClause;
- return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(d.moduleSpecifier)
- ? { importStatement: d, name: importClause.namedBindings.name, moduleSpecifier: d.moduleSpecifier }
- : undefined;
- // For known child node kinds of convertible imports, try again with parent node.
- case 244 /* NamespaceImport */:
- case 252 /* ExternalModuleReference */:
- case 91 /* ImportKeyword */:
- case 71 /* Identifier */:
- case 9 /* StringLiteral */:
- case 39 /* AsteriskToken */:
- break;
- default:
- return undefined;
- }
- node = node.parent;
- }
- }
- })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-///
-///
-///
///
-///
-///
///
///
///
@@ -99447,6 +99720,7 @@ var ts;
///
///
///
+///
///
///
///
@@ -99978,20 +100252,8 @@ var ts;
}
function getDeclarationName(declaration) {
var name = ts.getNameOfDeclaration(declaration);
- if (name) {
- var result_6 = ts.getTextOfIdentifierOrLiteral(name);
- if (result_6 !== undefined) {
- return result_6;
- }
- if (name.kind === 146 /* ComputedPropertyName */) {
- var expr = name.expression;
- if (expr.kind === 183 /* PropertyAccessExpression */) {
- return expr.name.text;
- }
- return ts.getTextOfIdentifierOrLiteral(expr);
- }
- }
- return undefined;
+ return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) :
+ name.kind === 146 /* ComputedPropertyName */ && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined);
}
function visit(node) {
switch (node.kind) {
@@ -100578,6 +100840,10 @@ var ts;
var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
return semanticDiagnostics.concat(declarationDiagnostics);
}
+ function getSuggestionDiagnostics(fileName) {
+ synchronizeHostData();
+ return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program);
+ }
function getCompilerOptionsDiagnostics() {
synchronizeHostData();
return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken));
@@ -100600,9 +100866,7 @@ var ts;
var sourceFile = getValidSourceFile(fileName);
var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (node === sourceFile) {
- return undefined;
- }
- if (ts.isLabelName(node)) {
+ // Avoid giving quickInfo for the sourceFile as a whole.
return undefined;
}
var typeChecker = program.getTypeChecker();
@@ -100611,6 +100875,11 @@ var ts;
// Try getting just type at this position and show
switch (node.kind) {
case 71 /* Identifier */:
+ if (ts.isLabelName(node)) {
+ // Type here will be 'any', avoid displaying this.
+ return undefined;
+ }
+ // falls through
case 183 /* PropertyAccessExpression */:
case 145 /* QualifiedName */:
case 99 /* ThisKeyword */:
@@ -100618,27 +100887,25 @@ var ts;
case 97 /* SuperKeyword */:
// For the identifiers/this/super etc get the type at position
var type = typeChecker.getTypeAtLocation(node);
- if (type) {
- return {
- kind: "" /* unknown */,
- kindModifiers: "" /* none */,
- textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
- displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)),
- documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type.symbol ? type.symbol.getJsDocTags() : undefined
- };
- }
+ return type && {
+ kind: "" /* unknown */,
+ kindModifiers: "" /* none */,
+ textSpan: ts.createTextSpanFromNode(node, sourceFile),
+ displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)),
+ documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined,
+ tags: type.symbol ? type.symbol.getJsDocTags() : undefined
+ };
}
return undefined;
}
- var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node);
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags;
return {
- kind: displayPartsDocumentationsAndKind.symbolKind,
+ kind: symbolKind,
kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
- textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
- displayParts: displayPartsDocumentationsAndKind.displayParts,
- documentation: displayPartsDocumentationsAndKind.documentation,
- tags: displayPartsDocumentationsAndKind.tags
+ textSpan: ts.createTextSpanFromNode(node, sourceFile),
+ displayParts: displayParts,
+ documentation: documentation,
+ tags: tags,
};
}
function getSymbolAtLocationForQuickInfo(node, checker) {
@@ -100646,11 +100913,9 @@ var ts;
&& ts.isPropertyAssignment(node.parent)
&& node.parent.name === node) {
var type = checker.getContextualType(node.parent.parent);
- if (type) {
- var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node));
- if (property) {
- return property;
- }
+ var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node));
+ if (property) {
+ return property;
}
}
return checker.getSymbolAtLocation(node);
@@ -100913,7 +101178,7 @@ var ts;
ts.Debug.assert(scope.type === "file");
var sourceFile = getValidSourceFile(scope.fileName);
var formatContext = ts.formatting.getFormatContext(formatOptions);
- return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host);
+ return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program);
}
function applyCodeActionCommand(fileName, actionOrUndefined) {
var action = typeof fileName === "string" ? actionOrUndefined : fileName;
@@ -100927,6 +101192,7 @@ var ts;
: Promise.reject("Host does not implement `installPackage`");
default:
ts.Debug.fail();
+ // TODO: Debug.assertNever(action); will only work if there is more than one type.
}
}
function getDocCommentTemplateAtPosition(fileName, position) {
@@ -101010,7 +101276,7 @@ var ts;
if (!ts.isInComment(sourceFile, matchPosition)) {
continue;
}
- var descriptor = undefined;
+ var descriptor = void 0;
for (var i = 0; i < descriptors.length; i++) {
if (matchArray[i + firstDescriptorCaptureIndex]) {
descriptor = descriptors[i];
@@ -101121,6 +101387,7 @@ var ts;
cleanupSemanticCache: cleanupSemanticCache,
getSyntacticDiagnostics: getSyntacticDiagnostics,
getSemanticDiagnostics: getSemanticDiagnostics,
+ getSuggestionDiagnostics: getSuggestionDiagnostics,
getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics,
getSyntacticClassifications: getSyntacticClassifications,
getSemanticClassifications: getSemanticClassifications,
@@ -101238,20 +101505,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_7 = [];
+ var result_6 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072 /* Union */) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_7.push(symbol);
+ result_6.push(symbol);
}
});
- return result_7;
+ return result_6;
}
if (symbol) {
- result_7.push(symbol);
- return result_7;
+ result_6.push(symbol);
+ return result_6;
}
}
return undefined;
@@ -101587,6 +101854,7 @@ var ts;
server.stringifyIndented = stringifyIndented;
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
+// tslint:disable no-unnecessary-qualifier
/**
* Declaration module describing the TypeScript Server protocol
*/
@@ -101637,6 +101905,7 @@ var ts;
CommandTypes["GeterrForProject"] = "geterrForProject";
CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync";
CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync";
+ CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync";
CommandTypes["NavBar"] = "navbar";
/* @internal */
CommandTypes["NavBarFull"] = "navbar-full";
@@ -101645,6 +101914,7 @@ var ts;
CommandTypes["NavtoFull"] = "navto-full";
CommandTypes["NavTree"] = "navtree";
CommandTypes["NavTreeFull"] = "navtree-full";
+ /** @deprecated */
CommandTypes["Occurrences"] = "occurrences";
CommandTypes["DocumentHighlights"] = "documentHighlights";
/* @internal */
@@ -101822,7 +102092,7 @@ var ts;
end: scriptInfo.positionToLineOffset(diag.start + diag.length),
text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"),
code: diag.code,
- category: ts.DiagnosticCategory[diag.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(diag),
source: diag.source
};
}
@@ -101834,7 +102104,7 @@ var ts;
var end = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length));
var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n");
var code = diag.code, source = diag.source;
- var category = ts.DiagnosticCategory[diag.category].toLowerCase();
+ var category = ts.diagnosticCategoryName(diag);
return includeFileName ? { start: start, end: end, text: text, code: code, category: category, source: source, fileName: diag.file && diag.file.fileName } :
{ start: start, end: end, text: text, code: code, category: category, source: source };
}
@@ -102140,6 +102410,9 @@ var ts;
_a[server.CommandNames.SyntacticDiagnosticsSync] = function (request) {
return _this.requiredResponse(_this.getSyntacticDiagnosticsSync(request.arguments));
},
+ _a[server.CommandNames.SuggestionDiagnosticsSync] = function (request) {
+ return _this.requiredResponse(_this.getSuggestionDiagnosticsSync(request.arguments));
+ },
_a[server.CommandNames.Geterr] = function (request) {
_this.errorCheck.startNew(function (next) { return _this.getDiagnostics(next, request.arguments.delay, request.arguments.files); });
return _this.notRequired();
@@ -102382,28 +102655,23 @@ var ts;
this.send(res);
};
Session.prototype.semanticCheck = function (file, project) {
- try {
- var diags = server.emptyArray;
- if (!isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) {
- diags = project.getLanguageService().getSemanticDiagnostics(file);
- }
- var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); });
- this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag");
- }
- catch (err) {
- this.logError(err, "semantic check");
- }
+ var diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file)
+ ? server.emptyArray
+ : project.getLanguageService().getSemanticDiagnostics(file);
+ this.sendDiagnosticsEvent(file, project, diags, "semanticDiag");
};
Session.prototype.syntacticCheck = function (file, project) {
+ this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag");
+ };
+ Session.prototype.infoCheck = function (file, project) {
+ this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag");
+ };
+ Session.prototype.sendDiagnosticsEvent = function (file, project, diagnostics, kind) {
try {
- var diags = project.getLanguageService().getSyntacticDiagnostics(file);
- if (diags) {
- var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); });
- this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag");
- }
+ this.event({ file: file, diagnostics: diagnostics.map(function (diag) { return formatDiag(file, project, diag); }) }, kind);
}
catch (err) {
- this.logError(err, "syntactic check");
+ this.logError(err, kind);
}
};
Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) {
@@ -102413,21 +102681,30 @@ var ts;
var followMs = Math.min(ms, 200);
var index = 0;
var checkOne = function () {
- if (_this.changeSeq === seq) {
- var checkSpec_1 = checkList[index];
- index++;
- if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) {
- _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project);
- if (_this.changeSeq === seq) {
- next.immediate(function () {
- _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project);
- if (checkList.length > index) {
- next.delay(followMs, checkOne);
- }
- });
- }
- }
+ if (_this.changeSeq !== seq) {
+ return;
}
+ var _a = checkList[index], fileName = _a.fileName, project = _a.project;
+ index++;
+ if (!project.containsFile(fileName, requireOpen)) {
+ return;
+ }
+ _this.syntacticCheck(fileName, project);
+ if (_this.changeSeq !== seq) {
+ return;
+ }
+ next.immediate(function () {
+ _this.semanticCheck(fileName, project);
+ if (_this.changeSeq !== seq) {
+ return;
+ }
+ next.immediate(function () {
+ _this.infoCheck(fileName, project);
+ if (checkList.length > index) {
+ next.delay(followMs, checkOne);
+ }
+ });
+ });
};
if (checkList.length > index && this.changeSeq === seq) {
next.delay(ms, checkOne);
@@ -102481,7 +102758,7 @@ var ts;
message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine),
start: d.start,
length: d.length,
- category: ts.DiagnosticCategory[d.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(d),
code: d.code,
startLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start)),
endLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length))
@@ -102501,7 +102778,7 @@ var ts;
message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine),
start: d.start,
length: d.length,
- category: ts.DiagnosticCategory[d.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(d),
code: d.code,
source: d.source,
startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start),
@@ -102629,6 +102906,15 @@ var ts;
}
return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition);
};
+ Session.prototype.getSuggestionDiagnosticsSync = function (args) {
+ var configFile = this.getConfigFileAndProject(args).configFile;
+ if (configFile) {
+ // Currently there are no info diagnostics for config files.
+ return server.emptyArray;
+ }
+ // isSemantic because we don't want to info diagnostics in declaration files for JS-only users
+ return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, args.includeLinePosition);
+ };
Session.prototype.getDocumentHighlights = function (args, simplifiedResult) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var position = this.getPositionInFile(args, file);
@@ -103106,12 +103392,12 @@ var ts;
return undefined;
}
if (simplifiedResult) {
- var span_16 = helpItems.applicableSpan;
+ var span_15 = helpItems.applicableSpan;
return {
items: helpItems.items,
applicableSpan: {
- start: scriptInfo.positionToLineOffset(span_16.start),
- end: scriptInfo.positionToLineOffset(span_16.start + span_16.length)
+ start: scriptInfo.positionToLineOffset(span_15.start),
+ end: scriptInfo.positionToLineOffset(span_15.start + span_15.length)
},
selectedItemIndex: helpItems.selectedItemIndex,
argumentIndex: helpItems.argumentIndex,
@@ -103300,7 +103586,7 @@ var ts;
return locationOrSpan.line !== undefined;
};
Session.prototype.extractPositionAndRange = function (args, scriptInfo) {
- var position = undefined;
+ var position;
var textRange;
if (this.isLocation(args)) {
position = getPosition(args);
@@ -103399,7 +103685,7 @@ var ts;
return {};
};
Session.prototype.getStartAndEndPosition = function (args, scriptInfo) {
- var startPosition = undefined, endPosition = undefined;
+ var startPosition, endPosition;
if (args.startPosition !== undefined) {
startPosition = args.startPosition;
}
@@ -104498,8 +104784,12 @@ var ts;
if (this.isOpen) {
return this.switchToScriptVersionCache();
}
- // Else if the svc is uptodate with the text, we are good
- return !this.pendingReloadFromDisk && this.svc;
+ // If there is pending reload from the disk then, reload the text
+ if (this.pendingReloadFromDisk) {
+ this.reloadWithFileText();
+ }
+ // At this point if svc is present its valid
+ return this.svc;
};
TextStorage.prototype.getOrLoadText = function () {
if (this.text === undefined || this.pendingReloadFromDisk) {
@@ -105083,15 +105373,17 @@ var ts;
var filesWithChangedSetOfUnresolvedImports;
var filesWithInvalidatedResolutions;
var allFilesHaveInvalidatedResolution = false;
+ var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); });
+ var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
// The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
// The key in the map is source file's path.
// The values are Map of resolutions with key being name lookedup.
var resolvedModuleNames = ts.createMap();
var perDirectoryResolvedModuleNames = ts.createMap();
+ var nonRelaticeModuleNameCache = ts.createMap();
+ var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
var resolvedTypeReferenceDirectives = ts.createMap();
var perDirectoryResolvedTypeReferenceDirectives = ts.createMap();
- var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); });
- var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
/**
* 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
@@ -105164,6 +105456,7 @@ var ts;
}
function clearPerDirectoryResolutions() {
perDirectoryResolvedModuleNames.clear();
+ nonRelaticeModuleNameCache.clear();
perDirectoryResolvedTypeReferenceDirectives.clear();
}
function finishCachingPerDirectoryResolution() {
@@ -105177,7 +105470,7 @@ var ts;
clearPerDirectoryResolutions();
}
function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host);
+ var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache);
// return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
if (!resolutionHost.getGlobalCache) {
return primaryResult;
@@ -105223,15 +105516,8 @@ var ts;
perDirectoryResolution.set(name, resolution);
}
resolutionsInFile.set(name, resolution);
- if (resolution.failedLookupLocations) {
- if (existingResolution && existingResolution.failedLookupLocations) {
- watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution);
- }
- else {
- watchFailedLookupLocationOfResolution(resolution, 0);
- }
- }
- else if (existingResolution) {
+ watchFailedLookupLocationOfResolution(resolution);
+ if (existingResolution) {
stopWatchFailedLookupLocationOfResolution(existingResolution);
}
if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
@@ -105338,78 +105624,91 @@ var ts;
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
}
- function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) {
- var failedLookupLocations = resolution.failedLookupLocations;
- var existingFailedLookupLocations = existingResolution.failedLookupLocations;
- for (var index = 0; index < failedLookupLocations.length; index++) {
- if (index === existingFailedLookupLocations.length) {
- // Additional failed lookup locations, watch from this index
- watchFailedLookupLocationOfResolution(resolution, index);
- return;
- }
- else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) {
- // Different failed lookup locations,
- // Watch new resolution failed lookup locations from this index and
- // stop watching existing resolutions from this index
- watchFailedLookupLocationOfResolution(resolution, index);
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index);
- return;
- }
+ function watchFailedLookupLocationOfResolution(resolution) {
+ // No need to set the resolution refCount
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- // All new failed lookup locations are already watched (and are same),
- // Stop watching failed lookup locations of existing resolution after failed lookup locations length
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length);
- }
- function watchFailedLookupLocationOfResolution(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ if (resolution.refCount !== undefined) {
+ resolution.refCount++;
+ return;
+ }
+ resolution.refCount = 1;
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var setAtRoot = false;
+ for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- // If the failed lookup location path is not one of the supported extensions,
- // store it in the custom path
- if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
- customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
- }
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore;
if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- if (dirWatcher) {
- dirWatcher.refCount++;
+ // If the failed lookup location path is not one of the supported extensions,
+ // store it in the custom path
+ if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
+ }
+ if (dirPath === rootPath) {
+ setAtRoot = true;
}
else {
- directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ setDirectoryWatcher(dir, dirPath);
}
}
}
+ if (setAtRoot) {
+ setDirectoryWatcher(rootDir, rootPath);
+ }
+ }
+ function setDirectoryWatcher(dir, dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (dirWatcher) {
+ dirWatcher.refCount++;
+ }
+ else {
+ directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ }
}
function stopWatchFailedLookupLocationOfResolution(resolution) {
- if (resolution.failedLookupLocations) {
- stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0);
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- }
- function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ resolution.refCount--;
+ if (resolution.refCount) {
+ return;
+ }
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var removeAtRoot = false;
+ for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
- if (refCount) {
- if (refCount === 1) {
- customFailedLookupPaths.delete(failedLookupLocationPath);
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
+ if (!ignore) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
+ if (refCount) {
+ if (refCount === 1) {
+ customFailedLookupPaths.delete(failedLookupLocationPath);
+ }
+ else {
+ ts.Debug.assert(refCount > 1);
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ }
+ }
+ if (dirPath === rootPath) {
+ removeAtRoot = true;
}
else {
- ts.Debug.assert(refCount > 1);
- customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ removeDirectoryWatcher(dirPath);
}
}
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore;
- if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- // Do not close the watcher yet since it might be needed by other failed lookup locations.
- dirWatcher.refCount--;
- }
}
+ if (removeAtRoot) {
+ removeDirectoryWatcher(rootPath);
+ }
+ }
+ function removeDirectoryWatcher(dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ // Do not close the watcher yet since it might be needed by other failed lookup locations.
+ dirWatcher.refCount--;
}
function createDirectoryWatcher(directory, dirPath) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
@@ -106100,6 +106399,7 @@ var ts;
/*@internal*/
function Project(
/*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) {
+ var _this = this;
this.projectName = projectName;
this.projectKind = projectKind;
this.projectService = projectService;
@@ -106133,6 +106433,7 @@ var ts;
this.hasChangedAutomaticTypeDirectiveNames = false;
this.directoryStructureHost = directoryStructureHost;
this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || "");
+ this.getCanonicalFileName = this.projectService.toCanonicalFileName;
this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds);
if (!this.compilerOptions) {
this.compilerOptions = ts.getDefaultCompilerOptions();
@@ -106145,7 +106446,10 @@ var ts;
}
this.setInternalCompilerOptionsForEmittingJsFiles();
var host = this.projectService.host;
- if (host.trace) {
+ if (this.projectService.logger.loggingEnabled()) {
+ this.trace = function (s) { return _this.writeLog(s); };
+ }
+ else if (host.trace) {
this.trace = function (s) { return host.trace(s); };
}
if (host.realpath) {
@@ -106795,8 +107099,8 @@ var ts;
var sourceFiles = this.program.getSourceFiles();
var strBuilder = "\tFiles (" + sourceFiles.length + ")\n";
if (writeProjectFileNames) {
- for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) {
- var file = sourceFiles_9[_i];
+ for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
+ var file = sourceFiles_7[_i];
strBuilder += "\t" + file.fileName + "\n";
}
}
@@ -106885,7 +107189,7 @@ var ts;
// ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations);
if (this.projectService.globalPlugins) {
- var _loop_11 = function (globalPluginName) {
+ var _loop_12 = function (globalPluginName) {
// Skip empty names from odd commandline parses
if (!globalPluginName)
return "continue";
@@ -106900,7 +107204,7 @@ var ts;
// Enable global plugins with synthetic configuration entries
for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) {
var globalPluginName = _a[_i];
- _loop_11(globalPluginName);
+ _loop_12(globalPluginName);
}
}
};
@@ -108598,7 +108902,7 @@ var ts;
return projects;
function combineProjects(toAddInfo) {
if (toAddInfo !== info) {
- var _loop_12 = function (project) {
+ var _loop_13 = function (project) {
// Add the projects only if they can use symLink targets and not already in the list
if (project.languageServiceEnabled &&
!project.getCompilerOptions().preserveSymlinks &&
@@ -108614,7 +108918,7 @@ var ts;
};
for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) {
var project = _a[_i];
- _loop_12(project);
+ _loop_13(project);
}
}
}
@@ -108928,13 +109232,13 @@ var ts;
this.printProjects();
};
ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
- var _loop_13 = function (proj) {
+ var _loop_14 = function (proj) {
var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; });
result.push(proj.getChangesSinceVersion(knownProject && knownProject.version));
};
for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) {
var proj = currentProjects_1[_i];
- _loop_13(proj);
+ _loop_14(proj);
}
};
/* @internal */
@@ -109043,7 +109347,7 @@ var ts;
var excludeRules = [];
var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); });
var excludedFiles = [];
- var _loop_14 = function (name) {
+ var _loop_15 = function (name) {
var rule = this_2.safelist[name];
for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) {
var root = normalizedNames_1[_i];
@@ -109061,7 +109365,7 @@ var ts;
}
}
if (rule.exclude) {
- var _loop_15 = function (exclude) {
+ var _loop_16 = function (exclude) {
var processedRule = root.replace(rule.match, function () {
var groups = [];
for (var _i = 0; _i < arguments.length; _i++) {
@@ -109088,7 +109392,7 @@ var ts;
};
for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) {
var exclude = _d[_c];
- _loop_15(exclude);
+ _loop_16(exclude);
}
}
else {
@@ -109104,11 +109408,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_14(name);
+ _loop_15(name);
}
var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); });
var filesToKeep = [];
- var _loop_16 = function (i) {
+ var _loop_17 = function (i) {
if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) {
excludedFiles.push(normalizedNames[i]);
}
@@ -109146,7 +109450,7 @@ var ts;
};
var this_3 = this;
for (var i = 0; i < proj.rootFiles.length; i++) {
- _loop_16(i);
+ _loop_17(i);
}
proj.rootFiles = filesToKeep;
return excludedFiles;
@@ -109531,8 +109835,7 @@ var ts;
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
length: diagnostic.length,
- /// TODO: no need for the tolowerCase call
- category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(diagnostic),
code: diagnostic.code
};
}
@@ -109582,7 +109885,7 @@ var ts;
};
LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) {
var newLine = ts.getNewLineOrDefaultFromHost(this.host);
- return ts.realizeDiagnostics(diagnostics, newLine);
+ return realizeDiagnostics(diagnostics, newLine);
};
LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) {
var _this = this;
@@ -109620,6 +109923,10 @@ var ts;
return _this.realizeDiagnostics(diagnostics);
});
};
+ LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) {
+ var _this = this;
+ return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); });
+ };
LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () {
var _this = this;
return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () {
diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts
index 21ea143e8c5..2f467c9ffb0 100644
--- a/lib/typescript.d.ts
+++ b/lib/typescript.d.ts
@@ -1811,7 +1811,7 @@ declare namespace ts {
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined;
- getJsxIntrinsicTagNames(): Symbol[];
+ getJsxIntrinsicTagNamesAt(location: Node): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
@@ -2192,11 +2192,25 @@ declare namespace ts {
interface IndexType extends InstantiableType {
type: InstantiableType | UnionOrIntersectionType;
}
- interface ConditionalType extends InstantiableType {
+ interface ConditionalRoot {
+ node: ConditionalTypeNode;
checkType: Type;
extendsType: Type;
trueType: Type;
falseType: Type;
+ isDistributive: boolean;
+ inferTypeParameters: TypeParameter[];
+ outerTypeParameters?: TypeParameter[];
+ instantiations?: Map;
+ aliasSymbol: Symbol;
+ aliasTypeArguments: Type[];
+ }
+ interface ConditionalType extends InstantiableType {
+ root: ConditionalRoot;
+ checkType: Type;
+ extendsType: Type;
+ resolvedTrueType?: Type;
+ resolvedFalseType?: Type;
}
interface SubstitutionType extends InstantiableType {
typeParameter: TypeParameter;
@@ -2222,41 +2236,13 @@ declare namespace ts {
}
enum InferencePriority {
NakedTypeVariable = 1,
- MappedType = 2,
- ReturnType = 4,
- NoConstraints = 8,
- AlwaysStrict = 16,
+ HomomorphicMappedType = 2,
+ MappedTypeConstraint = 4,
+ ReturnType = 8,
+ NoConstraints = 16,
+ AlwaysStrict = 32,
+ PriorityImpliesUnion = 12,
}
- interface InferenceInfo {
- typeParameter: TypeParameter;
- candidates: Type[];
- contraCandidates: Type[];
- inferredType: Type;
- priority: InferencePriority;
- topLevel: boolean;
- isFixed: boolean;
- }
- enum InferenceFlags {
- None = 0,
- InferUnionTypes = 1,
- NoDefault = 2,
- AnyDefault = 4,
- }
- /**
- * Ternary values are defined such that
- * x & y is False if either x or y is False.
- * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
- * x & y is True if both x and y are True.
- * x | y is False if both x and y are False.
- * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
- * x | y is True if either x or y is True.
- */
- enum Ternary {
- False = 0,
- Maybe = 1,
- True = -1,
- }
- type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary;
interface JsFileExtensionInfo {
extension: string;
isMixedContent: boolean;
@@ -2292,7 +2278,8 @@ declare namespace ts {
enum DiagnosticCategory {
Warning = 0,
Error = 1,
- Message = 2,
+ Suggestion = 2,
+ Message = 3,
}
enum ModuleResolutionKind {
Classic = 1,
@@ -3301,7 +3288,8 @@ declare namespace ts {
function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression;
function isTemplateLiteral(node: Node): node is TemplateLiteral;
function isAssertionExpression(node: Node): node is AssertionExpression;
- function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement;
+ function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement;
+ function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement;
function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement;
function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause;
/** True if node is of a kind that may contain comment text. */
@@ -4336,6 +4324,7 @@ declare namespace ts {
cleanupSemanticCache(): void;
getSyntacticDiagnostics(fileName: string): Diagnostic[];
getSemanticDiagnostics(fileName: string): Diagnostic[];
+ getSuggestionDiagnostics(fileName: string): Diagnostic[];
getCompilerOptionsDiagnostics(): Diagnostic[];
/**
* @deprecated Use getEncodedSyntacticClassifications instead.
@@ -4746,7 +4735,7 @@ declare namespace ts {
argumentCount: number;
}
interface CompletionInfo {
- /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isGlobalCompletionScope`. */
+ /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */
isGlobalCompletion: boolean;
isMemberCompletion: boolean;
/**
diff --git a/lib/typescript.js b/lib/typescript.js
index 71de0f4e0b6..277567d22fe 100644
--- a/lib/typescript.js
+++ b/lib/typescript.js
@@ -949,11 +949,14 @@ var ts;
var InferencePriority;
(function (InferencePriority) {
InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
- InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType";
- InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType";
- InferencePriority[InferencePriority["NoConstraints"] = 8] = "NoConstraints";
- InferencePriority[InferencePriority["AlwaysStrict"] = 16] = "AlwaysStrict";
+ InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
+ InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint";
+ InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType";
+ InferencePriority[InferencePriority["NoConstraints"] = 16] = "NoConstraints";
+ InferencePriority[InferencePriority["AlwaysStrict"] = 32] = "AlwaysStrict";
+ InferencePriority[InferencePriority["PriorityImpliesUnion"] = 12] = "PriorityImpliesUnion";
})(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
+ /* @internal */
var InferenceFlags;
(function (InferenceFlags) {
InferenceFlags[InferenceFlags["None"] = 0] = "None";
@@ -970,6 +973,7 @@ var ts;
* x | y is Maybe if either x or y is Maybe, but neither x or y is True.
* x | y is True if either x or y is True.
*/
+ /* @internal */
var Ternary;
(function (Ternary) {
Ternary[Ternary["False"] = 0] = "False";
@@ -995,8 +999,16 @@ var ts;
(function (DiagnosticCategory) {
DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
- DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message";
+ DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
+ DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
})(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
+ /* @internal */
+ function diagnosticCategoryName(d, lowerCase) {
+ if (lowerCase === void 0) { lowerCase = true; }
+ var name = DiagnosticCategory[d.category];
+ return lowerCase ? name.toLowerCase() : name;
+ }
+ ts.diagnosticCategoryName = diagnosticCategoryName;
var ModuleResolutionKind;
(function (ModuleResolutionKind) {
ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
@@ -1426,6 +1438,68 @@ var ts;
ListFormat[ListFormat["Parameters"] = 1296] = "Parameters";
ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters";
})(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
+ /* @internal */
+ var PragmaKindFlags;
+ (function (PragmaKindFlags) {
+ PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
+ /**
+ * Triple slash comment of the form
+ * ///
+ */
+ PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
+ /**
+ * Single line comment of the form
+ * // @pragma-name argval1 argval2
+ * or
+ * /// @pragma-name argval1 argval2
+ */
+ PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
+ /**
+ * Multiline non-jsdoc pragma of the form
+ * /* @pragma-name argval1 argval2 * /
+ */
+ PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
+ PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
+ PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
+ })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
+ /**
+ * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas`
+ */
+ /* @internal */
+ function _contextuallyTypePragmas(args) {
+ return args;
+ }
+ // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
+ // fancy effectively defining it twice, once in value-space and once in type-space
+ /* @internal */
+ ts.commentPragmas = _contextuallyTypePragmas({
+ "reference": {
+ args: [
+ { name: "types", optional: true, captureSpan: true },
+ { name: "path", optional: true, captureSpan: true },
+ { name: "no-default-lib", optional: true }
+ ],
+ kind: 1 /* TripleSlashXML */
+ },
+ "amd-dependency": {
+ args: [{ name: "path" }, { name: "name", optional: true }],
+ kind: 1 /* TripleSlashXML */
+ },
+ "amd-module": {
+ args: [{ name: "name" }],
+ kind: 1 /* TripleSlashXML */
+ },
+ "ts-check": {
+ kind: 2 /* SingleLine */
+ },
+ "ts-nocheck": {
+ kind: 2 /* SingleLine */
+ },
+ "jsx": {
+ args: [{ name: "factory" }],
+ kind: 4 /* MultiLine */
+ },
+ });
})(ts || (ts = {}));
/*@internal*/
var ts;
@@ -1528,7 +1602,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "2.8";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".0";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -2752,19 +2826,21 @@ var ts;
}
ts.equalOwnProperties = equalOwnProperties;
function arrayToMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = createMap();
for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
var value = array_6[_i];
- result.set(makeKey(value), makeValue ? makeValue(value) : value);
+ result.set(makeKey(value), makeValue(value));
}
return result;
}
ts.arrayToMap = arrayToMap;
function arrayToNumericMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = [];
for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
var value = array_7[_i];
- result[makeKey(value)] = makeValue ? makeValue(value) : value;
+ result[makeKey(value)] = makeValue(value);
}
return result;
}
@@ -2773,6 +2849,20 @@ var ts;
return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; });
}
ts.arrayToSet = arrayToSet;
+ function arrayToMultiMap(values, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
+ var result = createMultiMap();
+ for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
+ var value = values_1[_i];
+ result.add(makeKey(value), makeValue(value));
+ }
+ return result;
+ }
+ ts.arrayToMultiMap = arrayToMultiMap;
+ function group(values, getGroupId) {
+ return arrayFrom(arrayToMultiMap(values, getGroupId).values());
+ }
+ ts.group = group;
function cloneMap(map) {
var clone = createMap();
copyEntries(map, clone);
@@ -2830,15 +2920,6 @@ var ts;
}
}
}
- function group(values, getGroupId) {
- var groupIdToGroup = createMultiMap();
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- groupIdToGroup.add(getGroupId(value), value);
- }
- return arrayFrom(groupIdToGroup.values());
- }
- ts.group = group;
/**
* Tests whether a value is an array.
*/
@@ -2958,7 +3039,6 @@ var ts;
return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; });
}
ts.formatStringFromArgs = formatStringFromArgs;
- ts.localizedDiagnosticMessages = undefined;
function getLocaleSpecificMessage(message) {
return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
}
@@ -3884,7 +3964,7 @@ var ts;
// Sort the offsets array using either the literal or canonical path representations.
includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive);
var _loop_2 = function (includeBasePath) {
- if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
+ if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
basePaths.push(includeBasePath);
}
};
@@ -4289,7 +4369,7 @@ var ts;
ts.matchedText = matchedText;
/** Return the object corresponding to the best pattern to match `candidate`. */
function findBestPatternMatch(values, getPattern, candidate) {
- var matchedValue = undefined;
+ var matchedValue;
// use length of prefix as betterness criteria
var longestMatchPrefixLength = -1;
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
@@ -4393,7 +4473,7 @@ var ts;
*/
/* @internal */
function setStackTraceLimit() {
- if (Error.stackTraceLimit < 100) {
+ if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
Error.stackTraceLimit = 100;
}
}
@@ -4788,7 +4868,7 @@ var ts;
return stat.size;
}
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return 0;
},
exit: function (exitCode) {
@@ -5481,6 +5561,7 @@ var ts;
Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
+ Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
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}'."),
@@ -5552,7 +5633,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}'."),
- 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.Message, "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."),
+ 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}'."),
Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
@@ -5725,7 +5806,7 @@ var ts;
Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
- Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."),
+ Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
@@ -5769,6 +5850,7 @@ var ts;
Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."),
+ Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."),
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."),
@@ -5848,10 +5930,15 @@ var ts;
JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
+ JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
+ File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
+ This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
+ Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
+ JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
@@ -5892,6 +5979,9 @@ var ts;
Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
+ Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
+ Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
+ Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
};
})(ts || (ts = {}));
///
@@ -8162,8 +8252,7 @@ var ts;
}
ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
function isAmbientModule(node) {
- return node && node.kind === 237 /* ModuleDeclaration */ &&
- (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
+ return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
}
ts.isAmbientModule = isAmbientModule;
function isModuleWithStringLiteralName(node) {
@@ -8194,21 +8283,22 @@ var ts;
}
ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
function isExternalModuleAugmentation(node) {
+ return isAmbientModule(node) && isModuleAugmentationExternal(node);
+ }
+ ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ function isModuleAugmentationExternal(node) {
// external module augmentation is a ambient module declaration that is either:
// - 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
- if (!node || !isAmbientModule(node)) {
- return false;
- }
switch (node.parent.kind) {
case 272 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 238 /* ModuleBlock */:
- return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
+ return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
}
return false;
}
- ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
function isEffectiveExternalModule(node, compilerOptions) {
return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
}
@@ -9524,16 +9614,9 @@ var ts;
return false;
}
ts.isNodeDescendantOf = isNodeDescendantOf;
- // True if the given identifier, string literal, or number literal is the name of a declaration node
+ // True if `name` is the name of a declaration node
function isDeclarationName(name) {
- switch (name.kind) {
- case 71 /* Identifier */:
- case 9 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- return ts.isDeclaration(name.parent) && name.parent.name === name;
- default:
- return false;
- }
+ return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
}
ts.isDeclarationName = isDeclarationName;
// See GH#16030
@@ -9660,38 +9743,6 @@ var ts;
return undefined;
}
ts.getAncestor = getAncestor;
- function getFileReferenceFromReferencePath(comment, commentRange) {
- var simpleReferenceRegEx = /^\/\/\/\s*= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
}
ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
function textSpanIntersectsWith(span, start, length) {
- var end = start + length;
- return start <= textSpanEnd(span) && end >= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
}
ts.textSpanIntersectsWith = textSpanIntersectsWith;
function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
@@ -11361,12 +11400,9 @@ var ts;
}
ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
function textSpanIntersection(span1, span2) {
- var intersectStart = Math.max(span1.start, span2.start);
- var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
- if (intersectStart <= intersectEnd) {
- return createTextSpanFromBounds(intersectStart, intersectEnd);
- }
- return undefined;
+ var start = Math.max(span1.start, span2.start);
+ var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
+ return start <= end ? createTextSpanFromBounds(start, end) : undefined;
}
ts.textSpanIntersection = textSpanIntersection;
function createTextSpan(start, length) {
@@ -11631,6 +11667,7 @@ var ts;
return false;
}
try {
+ // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!)
ts.localizedDiagnosticMessages = JSON.parse(fileContents);
}
catch (e) {
@@ -12958,7 +12995,7 @@ var ts;
case 97 /* SuperKeyword */:
case 207 /* NonNullExpression */:
case 208 /* MetaProperty */:
- case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression
+ case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
return true;
default:
return false;
@@ -13043,7 +13080,6 @@ var ts;
|| isPartiallyEmittedExpression(node);
}
ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
- // Statement
function isIterationStatement(node, lookInLabeledStatements) {
switch (node.kind) {
case 218 /* ForStatement */:
@@ -14099,7 +14135,9 @@ var ts;
sourceFile.flags = contextFlags;
// Prime the scanner.
nextToken();
- processReferenceComments(sourceFile);
+ // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future
+ processCommentPragmas(sourceFile, sourceText);
+ processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
ts.Debug.assert(token() === 1 /* EndOfFileToken */);
sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
@@ -14112,6 +14150,9 @@ var ts;
fixupParentReferences(sourceFile);
}
return sourceFile;
+ function reportPragmaDiagnostic(pos, end, diagnostic) {
+ parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
+ }
}
function addJSDocComment(node) {
var comments = ts.getJSDocCommentRanges(node, sourceFile.text);
@@ -17089,8 +17130,9 @@ var ts;
var fullStart = scanner.getStartPos();
parseExpected(27 /* LessThanToken */);
if (token() === 29 /* GreaterThanToken */) {
- parseExpected(29 /* GreaterThanToken */);
+ // See below for explanation of scanJsxText
var node_1 = createNode(258 /* JsxOpeningFragment */, fullStart);
+ scanJsxText();
return finishNode(node_1);
}
var tagName = parseJsxElementName();
@@ -17137,7 +17179,9 @@ var ts;
}
function parseJsxExpression(inExpressionContext) {
var node = createNode(263 /* JsxExpression */);
- parseExpected(17 /* OpenBraceToken */);
+ if (!parseExpected(17 /* OpenBraceToken */)) {
+ return undefined;
+ }
if (token() !== 18 /* CloseBraceToken */) {
node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
node.expression = parseAssignmentExpressionOrHigher();
@@ -17332,7 +17376,7 @@ var ts;
case 48 /* AmpersandToken */: // foo &
case 49 /* BarToken */: // foo |
case 18 /* CloseBraceToken */: // foo }
- case 1 /* EndOfFileToken */:// foo
+ case 1 /* EndOfFileToken */: // foo
// these cases can't legally follow a type arg list. However, they're not legal
// expressions either. The user is probably in the middle of a generic type. So
// treat it as such.
@@ -17601,7 +17645,7 @@ var ts;
parseExpected(88 /* ForKeyword */);
var awaitToken = parseOptionalToken(121 /* AwaitKeyword */);
parseExpected(19 /* OpenParenToken */);
- var initializer = undefined;
+ var initializer;
if (token() !== 25 /* SemicolonToken */) {
if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) {
initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
@@ -18302,7 +18346,7 @@ var ts;
case 51 /* ExclamationToken */: // Non-null assertion on property name
case 56 /* ColonToken */: // Type Annotation for declaration
case 58 /* EqualsToken */: // Initializer for declaration
- case 55 /* QuestionToken */:// Not valid, but permitted so that it gets caught later on.
+ case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
return true;
default:
// Covers
@@ -18617,7 +18661,7 @@ var ts;
// import ModuleSpecifier;
if (identifier || // import id
token() === 39 /* AsteriskToken */ || // import *
- token() === 17 /* OpenBraceToken */) {
+ token() === 17 /* OpenBraceToken */) { // import {
node.importClause = parseImportClause(identifier, afterImportPos);
parseExpected(142 /* FromKeyword */);
}
@@ -18767,87 +18811,6 @@ var ts;
parseSemicolon();
return finishNode(node);
}
- function processReferenceComments(sourceFile) {
- var triviaScanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText);
- var referencedFiles = [];
- var typeReferenceDirectives = [];
- var amdDependencies = [];
- var amdModuleName;
- var checkJsDirective = undefined;
- // Keep scanning all the leading trivia in the file until we get to something that
- // isn't trivia. Any single line comment will be analyzed to see if it is a
- // reference comment.
- while (true) {
- var kind = triviaScanner.scan();
- if (kind !== 2 /* SingleLineCommentTrivia */) {
- if (ts.isTrivia(kind)) {
- continue;
- }
- else {
- break;
- }
- }
- var range = {
- kind: triviaScanner.getToken(),
- pos: triviaScanner.getTokenPos(),
- end: triviaScanner.getTextPos(),
- };
- var comment = sourceText.substring(range.pos, range.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range);
- if (referencePathMatchResult) {
- var fileReference = referencePathMatchResult.fileReference;
- sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var diagnosticMessage = referencePathMatchResult.diagnosticMessage;
- if (fileReference) {
- if (referencePathMatchResult.isTypeReferenceDirective) {
- typeReferenceDirectives.push(fileReference);
- }
- else {
- referencedFiles.push(fileReference);
- }
- }
- if (diagnosticMessage) {
- parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage));
- }
- }
- else {
- var amdModuleNameRegEx = /^\/\/\/\s* context.checkJsDirective.pos) {
+ context.checkJsDirective = {
+ enabled: key === "ts-check",
+ end: entry.range.end,
+ pos: entry.range.pos
+ };
+ }
+ });
+ break;
+ }
+ case "jsx": return; // Accessed directly
+ default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
+ }
+ });
+ }
+ ts.processPragmasIntoFields = processPragmasIntoFields;
+ var namedArgRegExCache = ts.createMap();
+ function getNamedArgRegEx(name) {
+ if (namedArgRegExCache.has(name)) {
+ return namedArgRegExCache.get(name);
+ }
+ var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
+ namedArgRegExCache.set(name, result);
+ return result;
+ }
+ var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
+ var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
+ function extractPragmas(pragmas, range, text) {
+ var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text);
+ if (tripleSlash) {
+ var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
+ return;
+ }
+ if (pragma.args) {
+ var argument = {};
+ for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
+ var arg = _a[_i];
+ var matcher = getNamedArgRegEx(arg.name);
+ var matchResult = matcher.exec(text);
+ if (!matchResult && !arg.optional) {
+ return; // Missing required argument, don't parse
+ }
+ else if (matchResult) {
+ if (arg.captureSpan) {
+ var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
+ argument[arg.name] = {
+ value: matchResult[3],
+ pos: startPos,
+ end: startPos + matchResult[3].length
+ };
+ }
+ else {
+ argument[arg.name] = matchResult[3];
+ }
+ }
+ }
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ }
+ else {
+ pragmas.push({ name: name, args: { arguments: {}, range: range } });
+ }
+ return;
+ }
+ var singleLine = singleLinePragmaRegEx.exec(text);
+ if (singleLine) {
+ return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
+ }
+ var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
+ var multiLineMatch;
+ while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
+ addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
+ }
+ }
+ function addPragmaForMatch(pragmas, range, kind, match) {
+ if (!match)
+ return;
+ var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & kind)) {
+ return;
+ }
+ var args = match[2]; // Split on spaces and match up positionally with definition
+ var argument = getNamedPragmaArguments(pragma, args);
+ if (argument === "fail")
+ return; // Missing required argument, fail to parse it
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ return;
+ }
+ function getNamedPragmaArguments(pragma, text) {
+ if (!text)
+ return {};
+ if (!pragma.args)
+ return {};
+ var args = text.split(/\s+/);
+ var argMap = {};
+ for (var i = 0; i < pragma.args.length; i++) {
+ var argument = pragma.args[i];
+ if (!args[i] && !argument.optional) {
+ return "fail";
+ }
+ if (argument.captureSpan) {
+ return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
+ }
+ argMap[argument.name] = args[i];
+ }
+ return argMap;
+ }
})(ts || (ts = {}));
///
///
@@ -20299,7 +20465,7 @@ var ts;
ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
}
- return ts.getEscapedTextOfIdentifierOrLiteral(name);
+ return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
switch (node.kind) {
case 154 /* Constructor */:
@@ -20440,7 +20606,12 @@ var ts;
}
}
addDeclarationToSymbol(symbol, node, includes);
- symbol.parent = parent;
+ if (symbol.parent) {
+ ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ symbol.parent = parent;
+ }
return symbol;
}
function declareModuleMember(node, symbolFlags, symbolExcludes) {
@@ -21529,7 +21700,7 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
- if (ts.isExternalModuleAugmentation(node)) {
+ if (ts.isModuleAugmentationExternal(node)) {
declareModuleSymbol(node);
}
else {
@@ -21544,9 +21715,7 @@ var ts;
}
}
var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
- if (pattern) {
- (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol });
- }
+ file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
}
}
else {
@@ -21951,7 +22120,7 @@ var ts;
seenThisKeyword = true;
return;
case 160 /* TypePredicate */:
- return checkTypePredicate(node);
+ break; // Binding the children will handle everything
case 147 /* TypeParameter */:
return bindTypeParameter(node);
case 148 /* Parameter */:
@@ -22075,16 +22244,6 @@ var ts;
function bindAnonymousTypeWorker(node) {
return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
}
- function checkTypePredicate(node) {
- var parameterName = node.parameterName, type = node.type;
- if (parameterName && parameterName.kind === 71 /* Identifier */) {
- checkStrictModeIdentifier(parameterName);
- }
- if (parameterName && parameterName.kind === 173 /* ThisType */) {
- seenThisKeyword = true;
- }
- bind(type);
- }
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (ts.isExternalModule(file)) {
@@ -23757,8 +23916,11 @@ var ts;
}
ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
- var directoryToModuleNameMap = ts.createMap();
- var moduleNameToDirectoryMap = ts.createMap();
+ return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName);
+ }
+ ts.createModuleResolutionCache = createModuleResolutionCache;
+ /*@internal*/
+ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
function getOrCreateCacheForDirectory(directoryName) {
var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
@@ -23842,7 +24004,7 @@ var ts;
}
}
}
- ts.createModuleResolutionCache = createModuleResolutionCache;
+ ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
@@ -23853,7 +24015,7 @@ var ts;
var result = perFolderCache && perFolderCache.get(moduleName);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
}
else {
@@ -24043,7 +24205,7 @@ var ts;
trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
}
// string is for exact match
- var matchedPattern = undefined;
+ var matchedPattern;
if (state.compilerOptions.paths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
@@ -24319,7 +24481,7 @@ var ts;
var packageJsonPath = pathToPackageJson(nodeModuleDirectory);
if (directoryExists && host.fileExists(packageJsonPath)) {
var packageJsonContent = readJson(packageJsonPath, host);
- if (subModuleName === "") {
+ if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName
var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state);
if (typeof path === "string") {
subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1));
@@ -24415,7 +24577,7 @@ var ts;
}
else {
var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
- if (rest !== "") {
+ if (rest !== "") { // If "rest" is empty, we just did this search above.
var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName);
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId.
packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId;
@@ -24492,6 +24654,7 @@ var ts;
return "@types/" + getMangledNameForScopedPackage(packageName);
}
ts.getTypesPackageName = getTypesPackageName;
+ /* @internal */
function getMangledNameForScopedPackage(packageName) {
if (ts.startsWith(packageName, "@")) {
var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
@@ -24501,6 +24664,7 @@ var ts;
}
return packageName;
}
+ ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage;
/* @internal */
function getPackageNameFromAtTypesDirectory(mangledName) {
var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
@@ -24521,7 +24685,7 @@ var ts;
var result = cache && cache.get(containingDirectory);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
}
@@ -24828,7 +24992,7 @@ var ts;
node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement);
return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined;
},
- getJsxIntrinsicTagNames: getJsxIntrinsicTagNames,
+ getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
isOptionalParameter: function (node) {
node = ts.getParseTreeNode(node, ts.isParameter);
return node ? isOptionalParameter(node) : false;
@@ -24867,7 +25031,7 @@ var ts;
resolveName: function (name, location, meaning, excludeGlobals) {
return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
},
- getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); },
+ getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
@@ -24879,13 +25043,13 @@ var ts;
node = ts.getParseTreeNode(node, ts.isTypeNode);
return node && getTypeArgumentConstraint(node);
},
+ getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; },
};
var tupleTypes = [];
var unionTypes = ts.createMap();
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
- var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4 /* Property */, "unknown");
@@ -24954,6 +25118,7 @@ var ts;
var anyArrayType;
var autoArrayType;
var anyReadonlyArrayType;
+ var deferredGlobalNonNullableTypeAlias;
// The library files are only loaded when the feature is used.
// 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
@@ -24970,9 +25135,6 @@ var ts;
var deferredGlobalAsyncIteratorType;
var deferredGlobalAsyncIterableIteratorType;
var deferredGlobalTemplateStringsArrayType;
- var deferredJsxElementClassType;
- var deferredJsxElementType;
- var deferredJsxStatelessElementType;
var deferredNodes;
var deferredUnusedIdentifierNodes;
var flowLoopStart = 0;
@@ -24999,6 +25161,19 @@ var ts;
var potentialNewTargetCollisions = [];
var awaitedTypeStack = [];
var diagnostics = ts.createDiagnosticCollection();
+ // Suggestion diagnostics must have a file. Keyed by source file name.
+ var suggestionDiagnostics = ts.createMultiMap();
+ function addSuggestionDiagnostic(diag) {
+ suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
+ }
+ function addErrorOrSuggestionDiagnostic(isError, diag) {
+ if (isError) {
+ diagnostics.add(diag);
+ }
+ else {
+ addSuggestionDiagnostic(diag);
+ }
+ }
var TypeFacts;
(function (TypeFacts) {
TypeFacts[TypeFacts["None"] = 0] = "None";
@@ -25024,8 +25199,7 @@ var ts;
TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull";
TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy";
TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy";
- TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable";
- TypeFacts[TypeFacts["All"] = 8388607] = "All";
+ TypeFacts[TypeFacts["All"] = 4194303] = "All";
// The following members encode facts about particular kinds of types for use in the getTypeFacts function.
// The presence of a particular fact means that the given test is true for some (and possibly all) values
// of that kind of type.
@@ -25055,10 +25229,10 @@ var ts;
TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts";
TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts";
TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts";
- TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts";
- TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts";
- TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts";
- TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts";
+ TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts";
+ TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts";
+ TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts";
+ TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts";
TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts";
TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts";
})(TypeFacts || (TypeFacts = {}));
@@ -25090,12 +25264,6 @@ var ts;
var typeofType = createTypeofType();
var _jsxNamespace;
var _jsxFactoryEntity;
- var _jsxElementPropertiesName;
- var _hasComputedJsxElementPropertiesName = false;
- var _jsxElementChildrenPropertyName;
- var _hasComputedJsxElementChildrenPropertyName = false;
- /** Things we lazy load from the JSX namespace */
- var jsxTypes = ts.createUnderscoreEscapedMap();
var subtypeRelation = ts.createMap();
var assignableRelation = ts.createMap();
var definitelyAssignableRelation = ts.createMap();
@@ -25151,6 +25319,7 @@ var ts;
TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType";
TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject";
TypeIncludes[TypeIncludes["Union"] = 2048] = "Union";
+ TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard";
})(TypeIncludes || (TypeIncludes = {}));
var MembersOrExportsResolutionKind;
(function (MembersOrExportsResolutionKind) {
@@ -25298,7 +25467,23 @@ var ts;
};
}
}
- function getJsxNamespace() {
+ function getJsxNamespace(location) {
+ if (location) {
+ var file = ts.getSourceFileOfNode(location);
+ if (file) {
+ if (file.localJsxNamespace) {
+ return file.localJsxNamespace;
+ }
+ var jsxPragma = file.pragmas.get("jsx");
+ if (jsxPragma) {
+ var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
+ file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
+ if (file.localJsxFactory) {
+ return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
+ }
+ }
+ }
+ }
if (!_jsxNamespace) {
_jsxNamespace = "React";
if (compilerOptions.jsxFactory) {
@@ -25982,7 +26167,7 @@ var ts;
case 234 /* InterfaceDeclaration */:
case 236 /* EnumDeclaration */:
case 235 /* TypeAliasDeclaration */:
- case 237 /* ModuleDeclaration */:// For `namespace N { N; }`
+ case 237 /* ModuleDeclaration */: // For `namespace N { N; }`
return true;
default:
return false;
@@ -26294,7 +26479,15 @@ var ts;
combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
symbolFromModule || symbolFromVariable;
if (!symbol) {
- error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name));
+ var moduleName = getFullyQualifiedName(moduleSymbol);
+ var declarationName = ts.declarationNameToString(name);
+ var suggestion = getSuggestionForNonexistentModule(name, targetSymbol);
+ if (suggestion !== undefined) {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion);
+ }
+ else {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
+ }
}
return symbol;
}
@@ -26505,6 +26698,9 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
+ if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) {
+ addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
+ }
// merged symbol is module declaration symbol combined with all augmentations
return getMergedSymbol(sourceFile.symbol);
}
@@ -26526,10 +26722,8 @@ var ts;
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
}
- else if (noImplicitAny && moduleNotFoundError) {
- var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name);
- errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName);
- diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo));
+ else {
+ addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
}
// Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
return undefined;
@@ -26552,6 +26746,12 @@ var ts;
}
return undefined;
}
+ function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) {
+ var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
+ var errorInfo = packageId && ts.chainDiagnosticMessages(
+ /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name));
+ return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
+ }
// An external module with an 'export =' declaration resolves to the target of the 'export =' declaration,
// and an external module with no 'export =' declaration resolves to the module itself.
function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
@@ -26829,11 +27029,19 @@ var ts;
// If we are looking in value space, the parent meaning is value, other wise it is namespace
return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */;
}
- function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) {
+ function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
+ if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
return undefined;
}
- var visitedSymbolTables = [];
+ var id = "" + getSymbolId(symbol);
+ var visitedSymbolTables;
+ if (visitedSymbolTablesMap.has(id)) {
+ visitedSymbolTables = visitedSymbolTablesMap.get(id);
+ }
+ else {
+ visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
+ }
return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
/**
* @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)
@@ -26850,7 +27058,7 @@ var ts;
// If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
// If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
- !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing);
+ !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
}
function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) &&
@@ -26868,7 +27076,8 @@ var ts;
// Check if symbol is any of the alias
return ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
if (symbolFromSymbolTable.flags & 2097152 /* Alias */
- && symbolFromSymbolTable.escapedName !== "export="
+ && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
+ && symbolFromSymbolTable.escapedName !== "default" /* Default */
&& !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
// If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
&& (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) {
@@ -27105,6 +27314,7 @@ var ts;
}
}
function typeToString(type, enclosingDeclaration, flags, writer) {
+ if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer);
ts.Debug.assert(typeNode !== undefined, "should always get typenode");
@@ -27230,6 +27440,9 @@ var ts;
}
if (type.flags & 1024 /* UniqueESSymbol */) {
if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
+ if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
+ return ts.createTypeQueryNode(symbolToName(type.symbol, context, 107455 /* Value */, /*expectsIdentifier*/ false));
+ }
if (context.tracker.reportInaccessibleUniqueSymbolError) {
context.tracker.reportInaccessibleUniqueSymbolError();
}
@@ -27312,8 +27525,8 @@ var ts;
if (type.flags & 2097152 /* Conditional */) {
var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
- var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
- var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
+ var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
+ var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
if (type.flags & 4194304 /* Substitution */) {
@@ -27482,7 +27695,7 @@ var ts;
}
}
}
- var entityName = undefined;
+ var entityName = void 0;
var nameIdentifier = symbolToTypeReferenceName(type.symbol);
if (qualifiedName) {
ts.Debug.assert(!qualifiedName.right);
@@ -27936,8 +28149,8 @@ var ts;
return "(Anonymous function)";
}
}
- if (symbol.syntheticLiteralTypeOrigin) {
- var stringValue = symbol.syntheticLiteralTypeOrigin.value;
+ if (symbol.nameType && symbol.nameType.flags & 32 /* StringLiteral */) {
+ var stringValue = symbol.nameType.value;
if (!ts.isIdentifierText(stringValue, compilerOptions.target)) {
return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\"";
}
@@ -28245,7 +28458,7 @@ var ts;
parentType = getNonNullableType(parentType);
}
var propType = getTypeOfPropertyOfType(parentType, text);
- var declaredType = propType && getApparentTypeForLocation(propType, declaration.name);
+ var declaredType = propType && getConstraintForLocation(propType, declaration.name);
type = declaredType && getFlowTypeOfReference(declaration, declaredType) ||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
getIndexTypeOfType(parentType, 0 /* String */);
@@ -28677,6 +28890,7 @@ var ts;
if (getter && getter.body) {
type = getReturnTypeFromBody(getter);
}
+ // Otherwise, fall back to 'any'.
else {
if (noImplicitAny) {
if (setter) {
@@ -29548,8 +29762,18 @@ var ts;
error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3);
lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */);
}
+ var symbolLinks_1 = getSymbolLinks(lateSymbol);
+ if (!symbolLinks_1.nameType) {
+ // Retain link to name type so that it can be reused later
+ symbolLinks_1.nameType = type;
+ }
addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
- lateSymbol.parent = parent;
+ if (lateSymbol.parent) {
+ ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ lateSymbol.parent = parent;
+ }
return links.resolvedSymbol = lateSymbol;
}
}
@@ -29751,7 +29975,7 @@ var ts;
}
return [signature];
}
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
// Allow matching non-generic signatures to have excess parameters and different return types
var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true);
@@ -29768,7 +29992,7 @@ var ts;
// type is the union of the constituent return types.
function getUnionSignatures(types, kind) {
var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); });
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
var signature = _a[_i];
@@ -29899,7 +30123,7 @@ var ts;
else {
// Combinations of function, class, enum and module
var members = emptySymbols;
- var stringIndexInfo = undefined;
+ var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
}
@@ -29998,13 +30222,12 @@ var ts;
// Create a mapper from T to the current iteration type constituent. Then, if the
// mapped type is itself an instantiated type, combine the iteration mapper with the
// instantiation mapper.
- var iterationMapper = createTypeMapper([typeParameter], [t]);
- var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper;
+ var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t]));
var propType = instantiateType(templateType, templateMapper);
// If the current iteration type constituent is a string literal type, create a property.
// Otherwise, for type string create a string index signature.
if (t.flags & 32 /* StringLiteral */) {
- var propName = ts.escapeLeadingUnderscores(t.value);
+ var propName = getLateBoundNameFromType(t);
var modifiersProp = getPropertyOfType(modifiersType, propName);
var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
!(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
@@ -30021,7 +30244,7 @@ var ts;
prop.syntheticOrigin = propertySymbol;
prop.declarations = propertySymbol.declarations;
}
- prop.syntheticLiteralTypeOrigin = t;
+ prop.nameType = t;
members.set(propName, prop);
}
else if (t.flags & (1 /* Any */ | 2 /* String */)) {
@@ -30206,7 +30429,7 @@ var ts;
return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined;
}
function getDefaultConstraintOfConditionalType(type) {
- return getUnionType([type.trueType, type.falseType]);
+ return getUnionType([getTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]);
}
function getConstraintOfDistributiveConditionalType(type) {
// Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
@@ -30214,13 +30437,11 @@ var ts;
// with its constraint. We do this because if the constraint is a union type it will be distributed
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
- if (isDistributiveConditionalType(type)) {
+ if (type.root.isDistributive) {
var constraint = getConstraintOfType(type.checkType);
if (constraint) {
- var target = type.target || type;
- var mapper = createTypeMapper([target.checkType], [constraint]);
- var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper;
- return instantiateType(target, combinedMapper);
+ var mapper = createTypeMapper([type.root.checkType], [constraint]);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
}
}
return undefined;
@@ -30228,17 +30449,27 @@ var ts;
function getConstraintOfConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
- function getBaseConstraintOfType(type) {
+ function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) {
if (type.flags & (7372800 /* InstantiableNonPrimitive */ | 393216 /* UnionOrIntersection */)) {
var constraint = getResolvedBaseConstraint(type);
if (constraint !== noConstraintType && constraint !== circularConstraintType) {
return constraint;
}
}
- else if (type.flags & 524288 /* Index */) {
+ }
+ function getBaseConstraintOfType(type) {
+ var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type);
+ if (!constraint && type.flags & 524288 /* Index */) {
return stringType;
}
- return undefined;
+ return constraint;
+ }
+ /**
+ * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
+ * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
+ */
+ function getBaseConstraintOrType(type) {
+ return getBaseConstraintOfType(type) || type;
}
function hasNonCircularBaseConstraint(type) {
return getResolvedBaseConstraint(type) !== circularConstraintType;
@@ -30302,7 +30533,8 @@ var ts;
return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 2097152 /* Conditional */) {
- return getBaseConstraint(getConstraintOfConditionalType(t));
+ var constraint = getConstraintOfConditionalType(t);
+ return constraint && getBaseConstraint(constraint);
}
if (t.flags & 4194304 /* Substitution */) {
return getBaseConstraint(t.substitute);
@@ -30413,7 +30645,7 @@ var ts;
}
var propTypes = [];
var declarations = [];
- var commonType = undefined;
+ var commonType;
for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
var prop = props_1[_b];
if (prop.declarations) {
@@ -30670,7 +30902,7 @@ var ts;
var parameters = [];
var hasLiteralTypes = false;
var minArgumentCount = 0;
- var thisParameter = undefined;
+ var thisParameter = void 0;
var hasThisParameter = void 0;
var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
@@ -31197,6 +31429,7 @@ var ts;
if (ts.isEntityNameExpression(expr)) {
return expr;
}
+ // fall through;
}
return undefined;
}
@@ -31452,15 +31685,6 @@ var ts;
var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined);
return symbol && getTypeOfGlobalSymbol(symbol, arity);
}
- /**
- * Returns a type that is inside a namespace at the global scope, e.g.
- * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type
- */
- function getExportedTypeFromNamespace(namespace, name) {
- var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined);
- var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */);
- return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol);
- }
/**
* Instantiates a global type that is generic with some element type, and returns that instantiation.
*/
@@ -31572,6 +31796,8 @@ var ts;
}
else if (flags & 1 /* Any */) {
includes |= 1 /* Any */;
+ if (type === wildcardType)
+ includes |= 4096 /* Wildcard */;
}
else if (!strictNullChecks && flags & 12288 /* Nullable */) {
if (flags & 4096 /* Undefined */)
@@ -31692,7 +31918,7 @@ var ts;
var typeSet = [];
var includes = addTypesToUnion(typeSet, 0, types);
if (includes & 1 /* Any */) {
- return anyType;
+ return includes & 4096 /* Wildcard */ ? wildcardType : anyType;
}
switch (unionReduction) {
case 1 /* Literal */:
@@ -31785,6 +32011,8 @@ var ts;
}
else if (flags & 1 /* Any */) {
includes |= 1 /* Any */;
+ if (type === wildcardType)
+ includes |= 4096 /* Wildcard */;
}
else if (flags & 16384 /* Never */) {
includes |= 8 /* Never */;
@@ -31835,7 +32063,7 @@ var ts;
return neverType;
}
if (includes & 1 /* Any */) {
- return anyType;
+ return includes & 4096 /* Wildcard */ ? wildcardType : anyType;
}
if (includes & 1024 /* EmptyObject */ && !(includes & 512 /* ObjectType */)) {
typeSet.push(emptyObjectType);
@@ -31877,19 +32105,30 @@ var ts;
return type.resolvedIndexType;
}
function getLiteralTypeFromPropertyName(prop) {
- return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ?
- neverType :
- getLiteralType(ts.symbolName(prop));
+ var links = getSymbolLinks(prop);
+ if (!links.nameType) {
+ if (links.target) {
+ ts.Debug.assert(links.target.escapedName === prop.escapedName, "Target symbol and symbol do not have the same name");
+ links.nameType = getLiteralTypeFromPropertyName(links.target);
+ }
+ else {
+ links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ?
+ neverType :
+ getLiteralType(ts.symbolName(prop));
+ }
+ }
+ return links.nameType;
}
function getLiteralTypeFromPropertyNames(type) {
return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName));
}
function getIndexType(type) {
- return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) :
- ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) :
- type === wildcardType ? wildcardType :
- type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType :
- getLiteralTypeFromPropertyNames(type);
+ return type.flags & 262144 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) :
+ maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) :
+ ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) :
+ type === wildcardType ? wildcardType :
+ type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType :
+ getLiteralTypeFromPropertyNames(type);
}
function getIndexTypeOrString(type) {
var indexType = getIndexType(type);
@@ -32050,10 +32289,13 @@ var ts;
}
function substituteIndexedMappedType(objectType, type) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper;
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
}
function getIndexedAccessType(objectType, indexType, accessNode) {
+ if (objectType === wildcardType || indexType === wildcardType) {
+ return wildcardType;
+ }
// If the index type is generic, or if the object type is generic and doesn't originate in an expression,
// we are performing a higher-order index access where we cannot meaningfully access the properties of the
// object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
@@ -32113,73 +32355,62 @@ var ts;
function getActualTypeParameter(type) {
return type.flags & 4194304 /* Substitution */ ? type.typeParameter : type;
}
- function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) {
- var type = createType(2097152 /* Conditional */);
- type.checkType = checkType;
- type.extendsType = extendsType;
- type.trueType = trueType;
- type.falseType = falseType;
- type.inferTypeParameters = inferTypeParameters;
- type.target = target;
- type.mapper = mapper;
- type.aliasSymbol = aliasSymbol;
- type.aliasTypeArguments = aliasTypeArguments;
- return type;
- }
- function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) {
- // Instantiate extends type without instantiating any 'infer T' type parameters
- var extendsType = instantiateType(baseExtendsType, mapper);
- // Return falseType for a definitely false extends check. We check an instantations 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 instatiations will be and we can just return the false branch type.
- if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) {
- return instantiateType(baseFalseType, mapper);
+ function getConditionalType(root, mapper) {
+ var checkType = instantiateType(root.checkType, mapper);
+ var extendsType = instantiateType(root.extendsType, mapper);
+ if (checkType === wildcardType || extendsType === wildcardType) {
+ return wildcardType;
}
- // The check could be true for some instantiation
- var combinedMapper;
- if (inferTypeParameters) {
- var inferences = ts.map(inferTypeParameters, createInferenceInfo);
- // 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(inferences, checkType, extendsType, 8 /* NoConstraints */ | 16 /* AlwaysStrict */);
- // We infer 'never' when there are no candidates for a type parameter
- var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; });
- var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes);
- combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper;
- }
- // Return union of trueType and falseType for any and never since they match anything
- if (checkType.flags & 1 /* Any */ || (checkType.flags & 16384 /* Never */ && !(extendsType.flags & 16384 /* Never */))) {
- return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]);
- }
- // Instantiate the extends type including inferences for 'infer T' type parameters
- var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType;
- // Return trueType for a definitely true extends check. The definitely assignable relation excludes
- // type variable constraints from consideration. Without the definitely assignable relation, the type
- // type Foo = T extends { x: string } ? string : number
- // would immediately resolve to 'string' instead of being deferred.
- if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) {
- return instantiateType(baseTrueType, combinedMapper || mapper);
+ // If this is a distributive conditional type and the check type is generic we need to defer
+ // resolution of the conditional type such that a later instantiation will properly distribute
+ // over union types.
+ if (!root.isDistributive || !maybeTypeOfKind(checkType, 7897088 /* Instantiable */)) {
+ var combinedMapper = void 0;
+ if (root.inferTypeParameters) {
+ var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
+ // 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, 16 /* NoConstraints */ | 32 /* AlwaysStrict */);
+ combinedMapper = combineTypeMappers(mapper, context);
+ }
+ // Return union of trueType and falseType for 'any' since it matches anything
+ if (checkType.flags & 1 /* Any */) {
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ }
+ // Instantiate the extends type including inferences for 'infer T' type parameters
+ var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
+ // Return falseType for a definitely false extends check. We check an instantations 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 instatiations will be and we can just return the false branch type.
+ if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) {
+ return instantiateType(root.falseType, mapper);
+ }
+ // Return trueType for a definitely true extends check. The definitely assignable relation excludes
+ // type variable constraints from consideration. Without the definitely assignable relation, the type
+ // type Foo = T extends { x: string } ? string : number
+ // would immediately resolve to 'string' instead of being deferred.
+ if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) {
+ return instantiateType(root.trueType, combinedMapper || mapper);
+ }
}
// Return a deferred type for a check that is neither definitely true nor definitely false
var erasedCheckType = getActualTypeParameter(checkType);
- var trueType = instantiateType(baseTrueType, mapper);
- var falseType = instantiateType(baseFalseType, mapper);
- // We compute the cache key from the ids of the four constituent types, plus an indicator of whether the
- // type is distributive (i.e. whether the original declaration has a type parameter as the check type).
- var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 /* TypeParameter */ ? 1 : 0;
- var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive;
- var cached = conditionalTypes.get(id);
- if (cached) {
- return cached;
- }
- var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper));
- conditionalTypes.set(id, result);
+ var result = createType(2097152 /* Conditional */);
+ result.root = root;
+ result.checkType = erasedCheckType;
+ result.extendsType = extendsType;
+ result.mapper = mapper;
+ result.aliasSymbol = root.aliasSymbol;
+ result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper);
return result;
}
- function isDistributiveConditionalType(type) {
- return !!((type.target || type).checkType.flags & 32768 /* TypeParameter */);
+ function getTrueTypeFromConditionalType(type) {
+ return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
+ }
+ function getFalseTypeFromConditionalType(type) {
+ return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -32195,7 +32426,28 @@ var ts;
function getTypeFromConditionalTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), /*target*/ undefined, /*mapper*/ undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node));
+ var checkType = getTypeFromTypeNode(node.checkType);
+ var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
+ var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
+ var root = {
+ node: node,
+ checkType: checkType,
+ extendsType: getTypeFromTypeNode(node.extendsType),
+ trueType: getTypeFromTypeNode(node.trueType),
+ falseType: getTypeFromTypeNode(node.falseType),
+ isDistributive: !!(checkType.flags & 32768 /* TypeParameter */),
+ inferTypeParameters: getInferTypeParameters(node),
+ outerTypeParameters: outerTypeParameters,
+ instantiations: undefined,
+ aliasSymbol: getAliasSymbolForTypeNode(node),
+ aliasTypeArguments: aliasTypeArguments
+ };
+ links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
+ if (outerTypeParameters) {
+ root.instantiations = ts.createMap();
+ root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
+ }
}
return links.resolvedType;
}
@@ -32540,14 +32792,18 @@ var ts;
return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
}
function isInferenceContext(mapper) {
- return !!mapper.signature;
+ return !!mapper.typeParameters;
}
function cloneTypeMapper(mapper) {
return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
+ createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
mapper;
}
function combineTypeMappers(mapper1, mapper2) {
+ if (!mapper1)
+ return mapper2;
+ if (!mapper2)
+ return mapper1;
return function (t) { return instantiateType(mapper1(t), mapper2); };
}
function createReplacementMapper(source, target, baseMapper) {
@@ -32729,22 +32985,35 @@ var ts;
return result;
}
function getConditionalTypeInstantiation(type, mapper) {
- var target = type.target || type;
- var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper;
+ 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, mapper);
+ var id = getTypeListId(typeArguments);
+ var result = root.instantiations.get(id);
+ if (!result) {
+ var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
+ result = instantiateConditionalType(root, newMapper);
+ root.instantiations.set(id, result);
+ }
+ return result;
+ }
+ return type;
+ }
+ function instantiateConditionalType(root, mapper) {
// 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).
- if (isDistributiveConditionalType(target)) {
- var checkType_1 = target.checkType;
- var instantiatedType = combinedMapper(checkType_1);
- if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072 /* Union */) {
- return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); });
+ if (root.isDistributive) {
+ var checkType_1 = root.checkType;
+ var instantiatedType = mapper(checkType_1);
+ if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 /* Union */ | 16384 /* Never */)) {
+ return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); });
}
}
- return instantiateConditionalType(target, combinedMapper);
- }
- function instantiateConditionalType(type, mapper) {
- return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments);
+ return getConditionalType(root, mapper);
}
function instantiateType(type, mapper) {
if (type && mapper && mapper !== identityMapper) {
@@ -32785,7 +33054,7 @@ var ts;
return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
}
if (type.flags & 2097152 /* Conditional */) {
- return getConditionalTypeInstantiation(type, mapper);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (type.flags & 4194304 /* Substitution */) {
return mapper(type.typeParameter);
@@ -33458,11 +33727,11 @@ var ts;
}
}
if (flags & 2097152 /* Conditional */) {
- if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
- if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) {
+ if (source.root.isDistributive === target.root.isDistributive) {
+ if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
+ if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
+ if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
return result;
}
}
@@ -33850,20 +34119,11 @@ var ts;
}
}
else if (source.flags & 2097152 /* Conditional */) {
- if (relation !== definitelyAssignableRelation) {
- var constraint = getConstraintOfDistributiveConditionalType(source);
- if (constraint) {
- if (result = isRelatedTo(constraint, target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
- }
- }
- }
if (target.flags & 2097152 /* Conditional */) {
if (isTypeIdenticalTo(source.checkType, target.checkType) &&
isTypeIdenticalTo(source.extendsType, target.extendsType)) {
- if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
- result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
+ if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
+ result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -33871,9 +34131,21 @@ var ts;
}
}
}
- else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
+ else if (relation !== definitelyAssignableRelation) {
+ var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
+ if (distributiveConstraint) {
+ if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ var defaultConstraint = getDefaultConstraintOfConditionalType(source);
+ if (defaultConstraint) {
+ if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
}
}
else {
@@ -34738,8 +35010,18 @@ var ts;
ts.Debug.assert(strictNullChecks);
return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]);
}
+ function getGlobalNonNullableTypeInstantiation(type) {
+ 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, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higherorder behavior
+ }
function getNonNullableType(type) {
- return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type;
+ return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
}
/**
* Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
@@ -34841,6 +35123,10 @@ var ts;
}
var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name);
result.type = undefinedType;
+ var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (associatedKeyType.flags & 32 /* StringLiteral */) {
+ result.nameType = associatedKeyType;
+ }
undefinedProperties.set(name, result);
return result;
}
@@ -35004,9 +35290,10 @@ var ts;
callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
}
}
- function createInferenceContext(signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo);
+ function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
+ var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(typeParameters, createInferenceInfo);
var context = mapper;
+ context.typeParameters = typeParameters;
context.signature = signature;
context.inferences = inferences;
context.flags = flags;
@@ -35125,7 +35412,7 @@ var ts;
var templateType = getTemplateTypeFromMappedType(target);
var inference = createInferenceInfo(typeParameter);
inferTypes([inference], sourceType, templateType);
- return getTypeFromInference(inference) || emptyObjectType;
+ return getTypeFromInference(inference);
}
function getUnmatchedProperty(source, target, requireOptionalProperties) {
var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
@@ -35143,18 +35430,29 @@ var ts;
function getTypeFromInference(inference) {
return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
- undefined;
+ emptyObjectType;
}
function inferTypes(inferences, originalSource, originalTarget, priority) {
if (priority === void 0) { priority = 0; }
var symbolStack;
var visited;
var contravariant = false;
+ var propagationType;
inferFromTypes(originalSource, originalTarget);
function inferFromTypes(source, target) {
if (!couldContainTypeVariables(target)) {
return;
}
+ if (source.flags & 1 /* Any */) {
+ // We are inferring from an 'any' type. We want to infer this type for every type parameter
+ // referenced in the target type, so we record it as the propagation type and infer from the
+ // target to itself. Then, as we find candidates we substitute the propagation type.
+ var savePropagationType = propagationType;
+ propagationType = source;
+ inferFromTypes(target, target);
+ propagationType = savePropagationType;
+ return;
+ }
if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
// Source and target are types originating in the same generic type alias declaration.
// Simply infer from source type arguments to target type arguments.
@@ -35224,14 +35522,15 @@ var ts;
inference.priority = priority;
}
if (priority === inference.priority) {
+ var candidate = propagationType || source;
if (contravariant) {
- inference.contraCandidates = ts.append(inference.contraCandidates, source);
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
}
else {
- inference.candidates = ts.append(inference.candidates, source);
+ inference.candidates = ts.append(inference.candidates, candidate);
}
}
- if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
}
}
@@ -35271,8 +35570,8 @@ var ts;
else if (source.flags & 2097152 /* Conditional */ && target.flags & 2097152 /* Conditional */) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(source.trueType, target.trueType);
- inferFromTypes(source.falseType, target.falseType);
+ inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
+ inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
}
else if (target.flags & 393216 /* UnionOrIntersection */) {
var targetTypes = target.types;
@@ -35308,7 +35607,7 @@ var ts;
}
}
else {
- if (!(priority && 8 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) {
+ if (!(priority & 16 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) {
source = getApparentType(source);
}
if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) {
@@ -35339,7 +35638,7 @@ var ts;
}
}
function inferFromContravariantTypes(source, target) {
- if (strictFunctionTypes || priority & 16 /* AlwaysStrict */) {
+ if (strictFunctionTypes || priority & 32 /* AlwaysStrict */) {
contravariant = !contravariant;
inferFromTypes(source, target);
contravariant = !contravariant;
@@ -35378,7 +35677,7 @@ var ts;
var inferredType = inferTypeForHomomorphicMappedType(source, target);
if (inferredType) {
var savePriority = priority;
- priority |= 2 /* MappedType */;
+ priority |= 2 /* HomomorphicMappedType */;
inferFromTypes(inferredType, inference.typeParameter);
priority = savePriority;
}
@@ -35388,7 +35687,10 @@ var ts;
if (constraintType.flags & 32768 /* TypeParameter */) {
// We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
// parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
+ var savePriority = priority;
+ priority |= 4 /* MappedTypeConstraint */;
inferFromTypes(getIndexType(source), constraintType);
+ priority = savePriority;
inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target));
return;
}
@@ -35497,58 +35799,63 @@ var ts;
var inference = context.inferences[index];
var inferredType = inference.inferredType;
if (!inferredType) {
- if (inference.candidates) {
- // Extract all object literal types and replace them with a single widened and normalized type.
- var candidates = widenObjectLiteralCandidates(inference.candidates);
- // We widen inferred literal types if
- // all inferences were made to top-level ocurrences of the type parameter, and
- // the type parameter has no constraint or its constraint includes no primitive or literal types, and
- // the type parameter was fixed during inference or does not occur at top-level in the return type.
- var signature = context.signature;
- var widenLiteralTypes = inference.topLevel &&
- !hasPrimitiveConstraint(inference.typeParameter) &&
- (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
- var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
- // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if
- // union types were requested or if all inferences were made from the return type position, infer a
- // union type. Otherwise, infer a common supertype.
- var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ?
- getUnionType(baseCandidates, 2 /* Subtype */) :
- getCommonSupertype(baseCandidates);
- inferredType = getWidenedType(unwidenedType);
- // If we have inferred 'never' but have contravariant candidates. To get a more specific type we
- // infer from the contravariant candidates instead.
- if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) {
+ var signature = context.signature;
+ if (signature) {
+ if (inference.candidates) {
+ // Extract all object literal types and replace them with a single widened and normalized type.
+ var candidates = widenObjectLiteralCandidates(inference.candidates);
+ // We widen inferred literal types if
+ // all inferences were made to top-level ocurrences of the type parameter, and
+ // the type parameter has no constraint or its constraint includes no primitive or literal types, and
+ // the type parameter was fixed during inference or does not occur at top-level in the return type.
+ var widenLiteralTypes = inference.topLevel &&
+ !hasPrimitiveConstraint(inference.typeParameter) &&
+ (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
+ var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
+ // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if
+ // union types were requested or if all inferences were made from the return type position, infer a
+ // union type. Otherwise, infer a common supertype.
+ var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 12 /* PriorityImpliesUnion */ ?
+ getUnionType(baseCandidates, 2 /* Subtype */) :
+ getCommonSupertype(baseCandidates);
+ inferredType = getWidenedType(unwidenedType);
+ // If we have inferred 'never' but have contravariant candidates. To get a more specific type we
+ // infer from the contravariant candidates instead.
+ if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) {
+ inferredType = getCommonSubtype(inference.contraCandidates);
+ }
+ }
+ else if (inference.contraCandidates) {
+ // We only have contravariant inferences, infer the best common subtype of those
inferredType = getCommonSubtype(inference.contraCandidates);
}
- }
- else if (inference.contraCandidates) {
- // We only have contravariant inferences, infer the best common subtype of those
- inferredType = getCommonSubtype(inference.contraCandidates);
- }
- else if (context.flags & 2 /* NoDefault */) {
- // We use silentNeverType as the wildcard that signals no inferences.
- inferredType = silentNeverType;
- }
- else {
- // Infer either the default or the empty object type when no inferences were
- // made. It is important to remember that in this case, inference still
- // succeeds, meaning there is no error for not having inference candidates. An
- // inference error only occurs when there are *conflicting* candidates, i.e.
- // candidates with no common supertype.
- var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
- if (defaultType) {
- // Instantiate the default type. Any forward reference to a type
- // parameter should be instantiated to the empty object type.
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ else if (context.flags & 2 /* NoDefault */) {
+ // We use silentNeverType as the wildcard that signals no inferences.
+ inferredType = silentNeverType;
}
else {
- inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */));
+ // Infer either the default or the empty object type when no inferences were
+ // made. It is important to remember that in this case, inference still
+ // succeeds, meaning there is no error for not having inference candidates. An
+ // inference error only occurs when there are *conflicting* candidates, i.e.
+ // candidates with no common supertype.
+ var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
+ if (defaultType) {
+ // Instantiate the default type. Any forward reference to a type
+ // parameter should be instantiated to the empty object type.
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ }
+ else {
+ inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */));
+ }
}
}
+ else {
+ inferredType = getTypeFromInference(inference);
+ }
inferredType = getWidenedUniqueESSymbolType(inferredType);
inference.inferredType = inferredType;
- var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]);
+ var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
var instantiatedConstraint = instantiateType(constraint, context);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
@@ -35593,7 +35900,7 @@ var ts;
function getFlowCacheKey(node) {
if (node.kind === 71 /* Identifier */) {
var symbol = getResolvedSymbol(node);
- return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
+ return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
}
if (node.kind === 99 /* ThisKeyword */) {
return "0";
@@ -35812,8 +36119,8 @@ var ts;
}
if (flags & 65536 /* Object */) {
return isFunctionObjectType(type) ?
- strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ :
- strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */;
+ strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ :
+ strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */;
}
if (flags & (2048 /* Void */ | 4096 /* Undefined */)) {
return 2457472 /* UndefinedFacts */;
@@ -35825,7 +36132,7 @@ var ts;
return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */;
}
if (flags & 134217728 /* NonPrimitive */) {
- return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */;
+ return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */;
}
if (flags & 7897088 /* Instantiable */) {
return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType);
@@ -35833,7 +36140,7 @@ var ts;
if (flags & 393216 /* UnionOrIntersection */) {
return getTypeFactsOfTypes(type.types);
}
- return 8388607 /* All */;
+ return 4194303 /* All */;
}
function getTypeWithFacts(type, include) {
return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
@@ -36031,6 +36338,9 @@ var ts;
// is a union type, the mapping function is applied to each constituent type and a union
// of the resulting types is returned.
function mapType(type, mapper, noReductions) {
+ if (type.flags & 16384 /* Never */) {
+ return type;
+ }
if (!(type.flags & 131072 /* Union */)) {
return mapper(type);
}
@@ -36869,24 +37179,23 @@ var ts;
!(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */);
return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType;
}
- function isApparentTypePosition(node) {
+ function isConstraintPosition(node) {
var parent = node.parent;
return parent.kind === 183 /* PropertyAccessExpression */ ||
parent.kind === 185 /* CallExpression */ && parent.expression === node ||
parent.kind === 184 /* ElementAccessExpression */ && parent.expression === node ||
- parent.kind === 207 /* NonNullExpression */ ||
parent.kind === 180 /* BindingElement */ && parent.name === node && !!parent.initializer;
}
function typeHasNullableConstraint(type) {
return type.flags & 7372800 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */);
}
- function getApparentTypeForLocation(type, node) {
+ 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 (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) {
- return mapType(getWidenedType(type), getApparentType);
+ if (isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
+ return mapType(getWidenedType(type), getBaseConstraintOrType);
}
return type;
}
@@ -36963,7 +37272,7 @@ var ts;
checkCollisionWithCapturedThisVariable(node, node);
checkCollisionWithCapturedNewTargetVariable(node, node);
checkNestedBlockScopedBinding(node, symbol);
- var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node);
+ var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
var assignmentKind = ts.getAssignmentTargetKind(node);
if (assignmentKind) {
if (!(localOrExportSymbol.flags & 3 /* Variable */)) {
@@ -37613,7 +37922,7 @@ var ts;
var func = ts.getContainingFunction(node);
if (func) {
var functionFlags = ts.getFunctionFlags(func);
- if (functionFlags & 1 /* Generator */) {
+ if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
return undefined;
}
var contextualReturnType = getContextualReturnType(func);
@@ -37781,7 +38090,7 @@ var ts;
function getContextualTypeForChildJsxExpression(node) {
var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
// JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined;
}
function getContextualTypeForJsxExpression(node) {
@@ -37933,15 +38242,9 @@ var ts;
return anyType;
}
var isJs = ts.isInJavaScriptFile(node);
- return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes);
+ return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); });
}
- function getJsxSignaturesParameterTypes(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ false);
- }
- function getJsxSignaturesParameterTypesJs(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ true);
- }
- function getJsxSignaturesParameterTypesInternal(valueType, isJs) {
+ function getJsxSignaturesParameterTypes(valueType, isJs, context) {
// If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type
if (valueType.flags & 2 /* String */) {
return anyType;
@@ -37951,7 +38254,7 @@ var ts;
// For example:
// var CustomTag: "h1" = "h1";
// Hello World
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = valueType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -37977,21 +38280,21 @@ var ts;
return unknownType;
}
}
- return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0 /* None */);
+ return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */);
}
- function getJsxPropsTypeFromCallSignature(sig) {
+ function getJsxPropsTypeFromCallSignature(sig, context) {
var propsType = getTypeOfFirstParameterOfSignature(sig);
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
propsType = intersectTypes(intrinsicAttribs, propsType);
}
return propsType;
}
- function getJsxPropsTypeFromClassType(hostClassType, isJs) {
+ function getJsxPropsTypeFromClassType(hostClassType, isJs, context) {
if (isTypeAny(hostClassType)) {
return hostClassType;
}
- var propsName = getJsxElementPropertiesName();
+ var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context));
if (propsName === undefined) {
// There is no type ElementAttributesProperty, return 'any'
return anyType;
@@ -38013,14 +38316,14 @@ var ts;
else {
// Normal case -- add in IntrinsicClassElements and IntrinsicElements
var apparentAttributesType = attributesType;
- var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes);
+ var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
if (intrinsicClassAttribs !== unknownType) {
var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
apparentAttributesType = intersectTypes(typeParams
? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs))
: intrinsicClassAttribs, apparentAttributesType);
}
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
}
@@ -38028,18 +38331,12 @@ var ts;
}
}
}
- function getJsxPropsTypeFromConstructSignatureJs(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ true);
- }
- function getJsxPropsTypeFromConstructSignature(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ false);
- }
- function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) {
+ function getJsxPropsTypeFromConstructSignature(sig, isJs, context) {
var hostClassType = getReturnTypeOfSignature(sig);
if (hostClassType) {
- return getJsxPropsTypeFromClassType(hostClassType, isJs);
+ return getJsxPropsTypeFromClassType(hostClassType, isJs, context);
}
- return getJsxPropsTypeFromCallSignature(sig);
+ return getJsxPropsTypeFromCallSignature(sig, context);
}
// 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.
@@ -38329,9 +38626,13 @@ var ts;
}
typeFlags |= type.flags;
var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined;
- var prop = nameType && isTypeUsableAsLateBoundName(nameType)
+ var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType);
+ var prop = hasLateBoundName
? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */)
: createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName);
+ if (hasLateBoundName) {
+ prop.nameType = nameType;
+ }
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.
@@ -38455,7 +38756,7 @@ var ts;
}
function checkJsxSelfClosingElement(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode);
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxElement(node, checkMode) {
// Check attributes
@@ -38467,14 +38768,16 @@ var ts;
else {
checkExpression(node.closingElement.tagName);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxFragment(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode);
- if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) {
- error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory);
+ if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
+ error(node, compilerOptions.jsxFactory
+ ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
+ : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
/**
* Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
@@ -38519,7 +38822,7 @@ var ts;
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
var attributeDecl = _a[_i];
var member = attributeDecl.symbol;
@@ -38624,12 +38927,11 @@ var ts;
function checkJsxAttributes(node, checkMode) {
return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
}
- function getJsxType(name) {
- var jsxType = jsxTypes.get(name);
- if (jsxType === undefined) {
- jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType);
- }
- return jsxType;
+ function getJsxType(name, location) {
+ var namespace = getJsxNamespaceAt(location);
+ var exports = namespace && getExportsOfSymbol(namespace);
+ var typeSymbol = exports && getSymbol(exports, name, 793064 /* Type */);
+ return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType;
}
/**
* Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
@@ -38640,11 +38942,11 @@ var ts;
function getIntrinsicTagSymbol(node) {
var links = getNodeLinks(node);
if (!links.resolvedSymbol) {
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
if (intrinsicElementsType !== unknownType) {
// Property case
if (!ts.isIdentifier(node.tagName))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
if (intrinsicProp) {
links.jsxFlags |= 1 /* IntrinsicNamedElement */;
@@ -38697,7 +38999,7 @@ var ts;
var signature = signatures_3[_i];
if (signature.typeParameters) {
var isJavascript = ts.isInJavaScriptFile(node);
- var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */);
+ var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */);
var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext);
instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript));
}
@@ -38707,6 +39009,18 @@ var ts;
}
return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */);
}
+ function getJsxNamespaceAt(location) {
+ var namespaceName = getJsxNamespace(location);
+ var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
+ if (resolvedNamespace) {
+ var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */);
+ if (candidate) {
+ return candidate;
+ }
+ }
+ // JSX global fallback
+ return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined);
+ }
/**
* Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
* Get a single property from that container if existed. Report an error if there are more than one property.
@@ -38714,9 +39028,7 @@ var ts;
* @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
* if other string is given or the container doesn't exist, return undefined.
*/
- function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) {
- // JSX
- var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined);
+ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
// JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */);
// JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
@@ -38728,6 +39040,8 @@ var ts;
if (propertiesOfJsxElementAttribPropInterface.length === 0) {
return "";
}
+ // Element Attributes has one property, so the element attributes type will be the type of the corresponding
+ // property of the class instance type
else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
return propertiesOfJsxElementAttribPropInterface[0].escapedName;
}
@@ -38743,19 +39057,11 @@ var ts;
/// non-intrinsic elements' attributes type is 'any'),
/// or '' if it has 0 properties (which means every
/// non-intrinsic elements' attributes type is the element instance type)
- function getJsxElementPropertiesName() {
- if (!_hasComputedJsxElementPropertiesName) {
- _hasComputedJsxElementPropertiesName = true;
- _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer);
- }
- return _jsxElementPropertiesName;
+ function getJsxElementPropertiesName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
}
- function getJsxElementChildrenPropertyName() {
- if (!_hasComputedJsxElementChildrenPropertyName) {
- _hasComputedJsxElementChildrenPropertyName = true;
- _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer);
- }
- return _jsxElementChildrenPropertyName;
+ function getJsxElementChildrenPropertyName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
function getApparentTypeOfJsxPropsType(propsType) {
if (!propsType) {
@@ -38784,7 +39090,7 @@ var ts;
function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
ts.Debug.assert(!(elementType.flags & 131072 /* Union */));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
// We don't call getResolvedSignature here because we have already resolve the type of JSX Element.
var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined);
@@ -38794,7 +39100,7 @@ var ts;
paramType = getApparentTypeOfJsxPropsType(paramType);
if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
// Intersect in JSX.IntrinsicAttributes if it exists
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
paramType = intersectTypes(intrinsicAttributes, paramType);
}
@@ -38819,7 +39125,7 @@ var ts;
ts.Debug.assert(!(elementType.flags & 131072 /* Union */));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
// Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
// We don't call getResolvedSignature because here we have already resolve the type of JSX Element.
var candidatesOutArray = [];
@@ -38853,7 +39159,7 @@ var ts;
result = allMatchingAttributesType;
}
// Intersect in JSX.IntrinsicAttributes if it exists
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
result = intersectTypes(intrinsicAttributes, result);
}
@@ -38896,7 +39202,7 @@ var ts;
// For example:
// var CustomTag: "h1" = "h1";
// Hello World
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = elementType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -38926,7 +39232,7 @@ var ts;
if (elementClassType) {
checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
}
- return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement));
+ return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement);
}
/**
* Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
@@ -38957,7 +39263,7 @@ var ts;
* @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component
*/
function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) {
- return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType());
+ return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node));
}
/**
* Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element.
@@ -38997,32 +39303,26 @@ var ts;
var prop = getPropertyOfType(attributesType, attrib.name.escapedText);
return prop || unknownSymbol;
}
- function getJsxGlobalElementClassType() {
- if (!deferredJsxElementClassType) {
- deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass);
- }
- return deferredJsxElementClassType;
+ function getJsxElementClassTypeAt(location) {
+ var type = getJsxType(JsxNames.ElementClass, location);
+ if (type === unknownType)
+ return undefined;
+ return type;
}
- function getJsxGlobalElementType() {
- if (!deferredJsxElementType) {
- deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element);
- }
- return deferredJsxElementType;
+ function getJsxElementTypeAt(location) {
+ return getJsxType(JsxNames.Element, location);
}
- function getJsxGlobalStatelessElementType() {
- if (!deferredJsxStatelessElementType) {
- var jsxElementType = getJsxGlobalElementType();
- if (jsxElementType) {
- deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]);
- }
+ function getJsxStatelessElementTypeAt(location) {
+ var jsxElementType = getJsxElementTypeAt(location);
+ if (jsxElementType) {
+ return getUnionType([jsxElementType, nullType]);
}
- return deferredJsxStatelessElementType;
}
/**
* Returns all the properties of the Jsx.IntrinsicElements interface
*/
- function getJsxIntrinsicTagNames() {
- var intrinsics = getJsxType(JsxNames.IntrinsicElements);
+ function getJsxIntrinsicTagNamesAt(location) {
+ var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
}
function checkJsxPreconditions(errorNode) {
@@ -39030,7 +39330,7 @@ var ts;
if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
}
- if (getJsxGlobalElementType() === undefined) {
+ if (getJsxElementTypeAt(errorNode) === undefined) {
if (noImplicitAny) {
error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
}
@@ -39045,7 +39345,7 @@ var ts;
// The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
// And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
- var reactNamespace = getJsxNamespace();
+ var reactNamespace = getJsxNamespace(node);
var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
var reactSym = resolveName(reactLocation, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
if (reactSym) {
@@ -39121,7 +39421,7 @@ var ts;
// If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type.
// but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass.
if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || getPropertiesOfType(sourceAttributesType).length > 0)) {
- error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName()));
+ error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement))));
}
else {
// Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties
@@ -39328,7 +39628,7 @@ var ts;
return unknownType;
}
}
- propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node);
+ propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
}
// 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,
@@ -39454,6 +39754,10 @@ var ts;
});
return result && ts.symbolName(result);
}
+ function getSuggestionForNonexistentModule(name, targetModule) {
+ var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
+ return suggestion && ts.symbolName(suggestion);
+ }
/**
* Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
* Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
@@ -39866,13 +40170,13 @@ var ts;
}
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
- var context = createInferenceContext(signature, 1 /* InferUnionTypes */, compareTypes);
+ var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes);
forEachMatchingParameterType(contextualSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target);
});
if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */);
+ inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration));
}
@@ -39923,7 +40227,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, 4 /* ReturnType */);
+ inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -40556,7 +40860,7 @@ var ts;
}
var candidate = void 0;
var inferenceContext = originalCandidate.typeParameters ?
- createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) :
+ createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) :
undefined;
while (true) {
candidate = originalCandidate;
@@ -41128,7 +41432,7 @@ var ts;
}
// Make sure require is not a local function
if (!ts.isIdentifier(node.expression))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
if (!resolvedRequire) {
// project does not contain symbol named 'require' - assume commonjs require
@@ -41320,7 +41624,7 @@ var ts;
}
else {
var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
- if (functionFlags & 1 /* Generator */) {
+ if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types);
if (!types || types.length === 0) {
var iterableIteratorAny = functionFlags & 2 /* Async */
@@ -41586,7 +41890,7 @@ var ts;
((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ?
checkAsyncFunctionReturnType(node) : // Async function
getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function
- if ((functionFlags & 1 /* Generator */) === 0) {
+ if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
// return is not necessary in the body of generators
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
}
@@ -41610,11 +41914,11 @@ var ts;
// its return type annotation.
var exprType = checkExpression(node.body);
if (returnOrPromisedType) {
- if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) {
+ if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body);
}
- else {
+ else { // Normal function
checkTypeAssignableTo(exprType, returnOrPromisedType, node.body);
}
}
@@ -42771,6 +43075,7 @@ var ts;
if (node.kind === 159 /* 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 === 162 /* FunctionType */ || node.kind === 232 /* FunctionDeclaration */ || node.kind === 163 /* ConstructorType */ ||
node.kind === 157 /* CallSignature */ || node.kind === 154 /* Constructor */ ||
node.kind === 158 /* ConstructSignature */) {
@@ -43589,7 +43894,7 @@ var ts;
case 230 /* VariableDeclaration */:
case 180 /* BindingElement */:
case 232 /* FunctionDeclaration */:
- case 246 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591
+ case 246 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
return 1 /* ExportValue */;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(d));
@@ -44113,7 +44418,7 @@ var ts;
var body = node.kind === 152 /* MethodSignature */ ? undefined : node.body;
checkSourceElement(body);
var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
- if ((functionFlags & 1 /* Generator */) === 0) {
+ if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */
? checkAsyncFunctionReturnType(node) // Async function
: getTypeFromTypeNode(returnTypeNode)); // normal function
@@ -44488,7 +44793,7 @@ var ts;
var symbol = getSymbolOfNode(node);
if (symbol.flags & 1 /* FunctionScopedVariable */) {
if (!ts.isIdentifier(node.name))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
if (localDeclarationSymbol &&
localDeclarationSymbol !== symbol &&
@@ -45191,7 +45496,7 @@ var ts;
var isGenerator = functionFlags & 1 /* Generator */;
if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) {
var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
- if (isGenerator) {
+ if (isGenerator) { // AsyncGenerator function or Generator function
// A generator does not need its return expressions checked against its return type.
// Instead, the yield expressions are checked against the element type.
// TODO: Check return types of generators when return type tracking is added
@@ -45209,7 +45514,7 @@ var ts;
}
}
else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) {
- if (functionFlags & 2 /* Async */) {
+ if (functionFlags & 2 /* Async */) { // Async function
var promisedType = getPromisedTypeOfPromise(returnType);
var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
if (promisedType) {
@@ -45651,7 +45956,7 @@ var ts;
var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
if (prop && baseProp) {
var rootChain = function () { return ts.chainDiagnosticMessages(
- /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); };
+ /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); };
if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
issuedMemberError = true;
}
@@ -46166,7 +46471,6 @@ var ts;
// - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
if (checkBody && node.body) {
- // body of ambient external module is always a module block
for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
var statement = _a[_i];
checkModuleAugmentationElement(statement, isGlobalAugmentation);
@@ -46271,7 +46575,11 @@ var ts;
}
function checkExternalImportOrExportDeclaration(node) {
var moduleName = ts.getExternalModuleName(node);
- if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) {
+ if (ts.nodeIsMissing(moduleName)) {
+ // Should be a parse error.
+ return false;
+ }
+ if (!ts.isStringLiteral(moduleName)) {
error(moduleName, ts.Diagnostics.String_literal_expected);
return false;
}
@@ -46282,7 +46590,7 @@ var ts;
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
return false;
}
- if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) {
+ if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
// we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration
// no need to do this again.
if (!isTopLevelInExternalModuleAugmentation(node)) {
@@ -47870,7 +48178,7 @@ var ts;
return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */);
},
writeLiteralConstValue: writeLiteralConstValue,
- getJsxFactoryEntity: function () { return _jsxFactoryEntity; }
+ getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }
};
// defined here to avoid outer scope pollution
function getTypeReferenceDirectivesForEntityName(node) {
@@ -49283,7 +49591,7 @@ var ts;
case 243 /* ImportClause */: // For default import
case 241 /* ImportEqualsDeclaration */:
case 244 /* NamespaceImport */:
- case 246 /* ImportSpecifier */:// For rename import `x as y`
+ case 246 /* ImportSpecifier */: // For rename import `x as y`
return true;
case 71 /* Identifier */:
// For regular import, `decl` is an Identifier under the ImportSpecifier.
@@ -49501,9 +49809,15 @@ var ts;
: node;
}
ts.updateQualifiedName = updateQualifiedName;
+ function parenthesizeForComputedName(expression) {
+ return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) ||
+ expression.kind === 296 /* CommaListExpression */ ?
+ createParen(expression) :
+ expression;
+ }
function createComputedPropertyName(expression) {
var node = createSynthesizedNode(146 /* ComputedPropertyName */);
- node.expression = expression;
+ node.expression = parenthesizeForComputedName(expression);
return node;
}
ts.createComputedPropertyName = createComputedPropertyName;
@@ -51300,7 +51614,7 @@ var ts;
var node = createSynthesizedNode(268 /* PropertyAssignment */);
node.name = asName(name);
node.questionToken = undefined;
- node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
+ node.initializer = ts.parenthesizeExpressionForList(initializer);
return node;
}
ts.createPropertyAssignment = createPropertyAssignment;
@@ -51410,6 +51724,12 @@ var ts;
updated.imports = node.imports;
if (node.moduleAugmentations !== undefined)
updated.moduleAugmentations = node.moduleAugmentations;
+ if (node.pragmas !== undefined)
+ updated.pragmas = node.pragmas;
+ if (node.localJsxFactory !== undefined)
+ updated.localJsxFactory = node.localJsxFactory;
+ if (node.localJsxNamespace !== undefined)
+ updated.localJsxNamespace = node.localJsxNamespace;
return updateNode(updated, node);
}
return node;
@@ -54339,7 +54659,7 @@ var ts;
var isDebugInfoEnabled = false;
Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */)
? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); }
- : ts.noop;
+ : ts.noop; // TODO: GH#22091
Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */)
? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); }
: ts.noop;
@@ -54444,7 +54764,7 @@ var ts;
var uniqueExports = ts.createMap();
var exportedNames;
var hasExportDefault = false;
- var exportEquals = undefined;
+ var exportEquals;
var hasExportStarsToExportValues = false;
var hasImportStarOrImportDefault = false;
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
@@ -56048,7 +56368,7 @@ var ts;
ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
var localName = ts.getMutableClone(name);
ts.setEmitFlags(localName, 1536 /* NoComments */);
- return ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)));
+ return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */));
}
/**
* Gets all property declarations with initializers on either the static or instance side of a class.
@@ -56711,6 +57031,8 @@ var ts;
// One of the individual is global object, return immediately
return serializedIndividual;
}
+ // If there exists union that is not void 0 expression, check if the the common type is identifier.
+ // anything more complex and we will just default to Object
else if (serializedUnion) {
// Different types
if (!ts.isIdentifier(serializedUnion) ||
@@ -56874,7 +57196,7 @@ var ts;
function visitPropertyNameOfClassElement(member) {
var name = member.name;
var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false);
- if (expr) {
+ if (expr) { // expr only exists if `name` is a computed property name
// Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order
if (ts.some(pendingExpressions)) {
expr = ts.inlineExpressions(pendingExpressions.concat([expr]));
@@ -59225,14 +59547,14 @@ var ts;
objectProperties = ts.createAssignHelper(context, segments);
}
}
- var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
return element;
}
function visitJsxOpeningFragment(node, children, isChild, location) {
- var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
@@ -60424,6 +60746,7 @@ var ts;
if (statement.kind === 223 /* ReturnStatement */) {
return true;
}
+ // An if-statement with two covered branches is covered.
else if (statement.kind === 215 /* IfStatement */) {
var ifStatement = statement;
if (ifStatement.elseStatement) {
@@ -60431,6 +60754,7 @@ var ts;
isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
}
}
+ // A block is covered if it has a last statement which is covered.
else if (statement.kind === 211 /* Block */) {
var lastStatement = ts.lastOrUndefined(statement.statements);
if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
@@ -60629,11 +60953,11 @@ var ts;
function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
initializer = ts.visitNode(initializer, visitor, ts.isExpression);
var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
- ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter))
- ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */));
+ ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
+ ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
- ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */);
+ ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
statements.push(statement);
}
/**
@@ -65222,6 +65546,7 @@ var ts;
withBlockStack.pop();
}
break;
+ // default: do nothing
}
}
}
@@ -66756,13 +67081,13 @@ var ts;
var importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
- text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}"
+ text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
var importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
- text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}"
+ text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
};
})(ts || (ts = {}));
///
@@ -68740,7 +69065,7 @@ var ts;
}
if (compilerOptions.mapRoot) {
sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot);
- if (sourceFileOrBundle.kind === 272 /* SourceFile */) {
+ if (sourceFileOrBundle.kind === 272 /* SourceFile */) { // emitting single module file
// For modules or multiple emit files the mapRoot will have directory structure like the sources
// So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir));
@@ -69609,8 +69934,8 @@ var ts;
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = ts.createMap();
}
- for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) {
- var directive = typeReferenceDirectives_1[_i];
+ for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
+ var directive = typeReferenceDirectives_2[_i];
if (!usedTypeDirectiveReferences.has(directive)) {
usedTypeDirectiveReferences.set(directive, directive);
}
@@ -69899,7 +70224,12 @@ var ts;
"?");
}
write(": ");
- emitType(node.type);
+ if (node.type) {
+ emitType(node.type);
+ }
+ else {
+ write("any");
+ }
write(";");
writeLine();
decreaseIndent();
@@ -69990,6 +70320,7 @@ var ts;
if (isModuleElementVisible) {
writeModuleElement(node);
}
+ // Import equals declaration in internal module can become visible as part of any emit so lets make sure we add these irrespective
else if (node.kind === 241 /* ImportEqualsDeclaration */ ||
(node.parent.kind === 272 /* SourceFile */ && isCurrentFileExternalModule)) {
var isVisible = void 0;
@@ -70543,6 +70874,8 @@ var ts;
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;
}
+ // 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 === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ ||
(node.kind === 148 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
@@ -71885,6 +72218,8 @@ var ts;
// Enum
case 271 /* EnumMember */:
return emitEnumMember(node);
+ // JSDoc nodes (ignored)
+ // Transformation nodes (ignored)
}
// If the node is an expression, try to emit it as an expression with
// substitution.
@@ -72080,7 +72415,8 @@ var ts;
else {
emitTypeAnnotation(node.type);
}
- emitInitializer(node.initializer);
+ // 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);
}
function emitDecorator(decorator) {
writePunctuation("@");
@@ -72102,8 +72438,9 @@ var ts;
emitModifiers(node, node.modifiers);
emit(node.name);
emitIfPresent(node.questionToken);
+ emitIfPresent(node.exclamationToken);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
writeSemicolon();
}
function emitMethodSignature(node) {
@@ -72348,7 +72685,7 @@ var ts;
writeSpace();
}
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
//
// Expressions
@@ -72385,7 +72722,10 @@ var ts;
emitExpression(node.expression);
increaseIndentIf(indentBeforeDot);
var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression);
- writePunctuation(shouldEmitDotDot ? ".." : ".");
+ if (shouldEmitDotDot) {
+ writePunctuation(".");
+ }
+ emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node);
increaseIndentIf(indentAfterDot);
emit(node.name);
decreaseIndentIf(indentBeforeDot, indentAfterDot);
@@ -72411,9 +72751,9 @@ var ts;
}
function emitElementAccessExpression(node) {
emitExpression(node.expression);
- writePunctuation("[");
+ var openPos = emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
emitExpression(node.argumentExpression);
- writePunctuation("]");
+ emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node);
}
function emitCallExpression(node) {
emitExpression(node.expression);
@@ -72421,7 +72761,7 @@ var ts;
emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */);
}
function emitNewExpression(node) {
- writeKeyword("new");
+ emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
emitTypeArguments(node, node.typeArguments);
@@ -72439,9 +72779,9 @@ var ts;
emitExpression(node.expression);
}
function emitParenthesizedExpression(node) {
- writePunctuation("(");
+ var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
}
function emitFunctionExpression(node) {
emitFunctionDeclarationOrExpression(node);
@@ -72459,22 +72799,22 @@ var ts;
emit(node.equalsGreaterThanToken);
}
function emitDeleteExpression(node) {
- writeKeyword("delete");
+ emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitTypeOfExpression(node) {
- writeKeyword("typeof");
+ emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitVoidExpression(node) {
- writeKeyword("void");
+ emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitAwaitExpression(node) {
- writeKeyword("await");
+ emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
@@ -72542,7 +72882,7 @@ var ts;
emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */);
}
function emitYieldExpression(node) {
- writeKeyword("yield");
+ emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node);
emit(node.asteriskToken);
emitExpressionWithLeadingSpace(node.expression);
}
@@ -72586,17 +72926,13 @@ var ts;
// Statements
//
function emitBlock(node) {
- writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
- // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted
- increaseIndent();
- emitLeadingCommentsOfPosition(node.statements.end);
- decreaseIndent();
- writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node);
}
function emitBlockStatements(node, forceSingleLine) {
+ emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */;
emitList(node, node.statements, format);
+ emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
}
function emitVariableStatement(node) {
emitModifiers(node, node.modifiers);
@@ -72611,15 +72947,15 @@ var ts;
writeSemicolon();
}
function emitIfStatement(node) {
- var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node);
+ var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.thenStatement);
if (node.elseStatement) {
writeLineOrSpace(node);
- writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
+ emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
if (node.elseStatement.kind === 215 /* IfStatement */) {
writeSpace();
emit(node.elseStatement);
@@ -72629,8 +72965,15 @@ var ts;
}
}
}
+ function emitWhileClause(node, startPos) {
+ var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node);
+ writeSpace();
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
+ emitExpression(node.expression);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
+ }
function emitDoStatement(node) {
- writeKeyword("do");
+ emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node);
emitEmbeddedStatement(node, node.statement);
if (ts.isBlock(node.statement)) {
writeSpace();
@@ -72638,55 +72981,48 @@ var ts;
else {
writeLineOrSpace(node);
}
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(");");
+ emitWhileClause(node, node.statement.end);
+ writePunctuation(";");
}
function emitWhileStatement(node) {
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(")");
+ emitWhileClause(node, node.pos);
emitEmbeddedStatement(node, node.statement);
}
function emitForStatement(node) {
- var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
+ var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
emitForBinding(node.initializer);
- writeSemicolon();
+ pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.condition);
- writeSemicolon();
+ pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.incrementor);
- writePunctuation(")");
+ emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForInStatement(node) {
- var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("in");
+ emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForOfStatement(node) {
- var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitWithTrailingSpace(node.awaitModifier);
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("of");
+ emitTokenWithComment(144 /* OfKeyword */, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForBinding(node) {
@@ -72700,22 +73036,34 @@ var ts;
}
}
function emitContinueStatement(node) {
- writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword);
+ emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
function emitBreakStatement(node) {
- writeToken(72 /* BreakKeyword */, node.pos, writeKeyword);
+ emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
- function emitTokenWithComment(token, pos, writer, contextNode) {
+ function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
var node = contextNode && ts.getParseTreeNode(contextNode);
- if (node && node.kind === contextNode.kind) {
+ var isSimilarNode = node && node.kind === contextNode.kind;
+ var startPos = pos;
+ if (isSimilarNode) {
pos = ts.skipTrivia(currentSourceFile.text, pos);
}
- pos = writeToken(token, pos, writer, /*contextNode*/ contextNode);
- if (node && node.kind === contextNode.kind) {
+ if (emitLeadingCommentsOfPosition && isSimilarNode) {
+ var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
+ if (needsIndent) {
+ increaseIndent();
+ }
+ emitLeadingCommentsOfPosition(startPos);
+ if (needsIndent) {
+ decreaseIndent();
+ }
+ }
+ pos = writeTokenText(token, writer, pos);
+ if (emitTrailingCommentsOfPosition && isSimilarNode) {
emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
}
return pos;
@@ -72726,35 +73074,35 @@ var ts;
writeSemicolon();
}
function emitWithStatement(node) {
- writeKeyword("with");
+ var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writePunctuation("(");
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitSwitchStatement(node) {
- var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
writeSpace();
emit(node.caseBlock);
}
function emitLabeledStatement(node) {
emit(node.label);
- writePunctuation(":");
+ emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node);
writeSpace();
emit(node.statement);
}
function emitThrowStatement(node) {
- writeKeyword("throw");
+ emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node);
emitExpressionWithLeadingSpace(node.expression);
writeSemicolon();
}
function emitTryStatement(node) {
- writeKeyword("try");
+ emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node);
writeSpace();
emit(node.tryBlock);
if (node.catchClause) {
@@ -72763,7 +73111,7 @@ var ts;
}
if (node.finallyBlock) {
writeLineOrSpace(node);
- writeKeyword("finally");
+ emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
writeSpace();
emit(node.finallyBlock);
}
@@ -72778,7 +73126,7 @@ var ts;
function emitVariableDeclaration(node) {
emit(node.name);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
}
function emitVariableDeclarationList(node) {
writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var");
@@ -72979,23 +73327,21 @@ var ts;
}
function emitModuleBlock(node) {
pushNameGenerationScope(node);
- writePunctuation("{");
emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
- writePunctuation("}");
popNameGenerationScope(node);
}
function emitCaseBlock(node) {
- writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation);
+ emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node);
emitList(node, node.clauses, 65 /* CaseBlockClauses */);
- writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation);
+ emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
}
function emitImportEqualsDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSpace();
- writePunctuation("=");
+ emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node);
writeSpace();
emitModuleReference(node.moduleReference);
writeSemicolon();
@@ -73010,12 +73356,12 @@ var ts;
}
function emitImportDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
if (node.importClause) {
emit(node.importClause);
writeSpace();
- writeKeyword("from");
+ emitTokenWithComment(142 /* FromKeyword */, node.importClause.end, writeKeyword, node);
writeSpace();
}
emitExpression(node.moduleSpecifier);
@@ -73024,15 +73370,15 @@ var ts;
function emitImportClause(node) {
emit(node.name);
if (node.name && node.namedBindings) {
- writePunctuation(",");
+ emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node);
writeSpace();
}
emit(node.namedBindings);
}
function emitNamespaceImport(node) {
- writePunctuation("*");
+ var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node);
writeSpace();
emit(node.name);
}
@@ -73043,41 +73389,42 @@ var ts;
emitImportOrExportSpecifier(node);
}
function emitExportAssignment(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
writeSpace();
if (node.isExportEquals) {
- writeOperator("=");
+ emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node);
}
else {
- writeKeyword("default");
+ emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node);
}
writeSpace();
emitExpression(node.expression);
writeSemicolon();
}
function emitExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
writeSpace();
if (node.exportClause) {
emit(node.exportClause);
}
else {
- writePunctuation("*");
+ nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node);
}
if (node.moduleSpecifier) {
writeSpace();
- writeKeyword("from");
+ var fromPos = node.exportClause ? node.exportClause.end : nextPos;
+ emitTokenWithComment(142 /* FromKeyword */, fromPos, writeKeyword, node);
writeSpace();
emitExpression(node.moduleSpecifier);
}
writeSemicolon();
}
function emitNamespaceExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeKeyword("as");
+ nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node);
writeSpace();
- writeKeyword("namespace");
+ nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSemicolon();
@@ -73097,7 +73444,7 @@ var ts;
if (node.propertyName) {
emit(node.propertyName);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
writeSpace();
}
emit(node.name);
@@ -73189,44 +73536,31 @@ var ts;
// Clauses
//
function emitCaseClause(node) {
- writeKeyword("case");
+ emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
}
function emitDefaultClause(node) {
- writeKeyword("default");
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node);
+ emitCaseOrDefaultClauseRest(node, node.statements, pos);
}
- function emitCaseOrDefaultClauseStatements(parentNode, statements) {
+ function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
var emitAsSingleStatement = statements.length === 1 &&
(
// treat synthesized nodes as located on the same line for emit purposes
ts.nodeIsSynthesized(parentNode) ||
ts.nodeIsSynthesized(statements[0]) ||
ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
- // e.g:
- // case 0: // Zero
- // case 1: // One
- // case 2: // two
- // return "hi";
- // If there is no statements, emitNodeWithComments of the parentNode which is caseClause will take care of trailing comment.
- // So in example above, comment "// Zero" and "// One" will be emit in emitTrailingComments in emitNodeWithComments.
- // However, for "case 2", because parentNode which is caseClause has an "end" property to be end of the statements (in this case return statement)
- // comment "// two" will not be emitted in emitNodeWithComments.
- // Therefore, we have to do the check here to emit such comment.
- if (statements.length > 0) {
- // We use emitTrailingCommentsOfPosition instead of emitLeadingCommentsOfPosition because leading comments is defined as comments before the node after newline character separating it from previous line
- // Note: we can't use parentNode.end as such position includes statements.
- emitTrailingCommentsOfPosition(statements.pos);
- }
var format = 81985 /* CaseOrDefaultClauseStatements */;
if (emitAsSingleStatement) {
+ writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode);
writeSpace();
format &= ~(1 /* MultiLine */ | 64 /* Indented */);
}
+ else {
+ emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode);
+ }
emitList(parentNode, statements, format);
}
function emitHeritageClause(node) {
@@ -73236,12 +73570,12 @@ var ts;
emitList(node, node.types, 272 /* HeritageClauseTypes */);
}
function emitCatchClause(node) {
- var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node);
writeSpace();
if (node.variableDeclaration) {
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emit(node.variableDeclaration);
- writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
writeSpace();
}
emit(node.block);
@@ -73287,7 +73621,7 @@ var ts;
//
function emitEnumMember(node) {
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
//
// Top-level nodes
@@ -73404,10 +73738,10 @@ var ts;
emit(node);
}
}
- function emitInitializer(node) {
+ function emitInitializer(node, equalCommentStartPos, container) {
if (node) {
writeSpace();
- writeOperator("=");
+ emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
writeSpace();
emitExpression(node);
}
@@ -73455,7 +73789,7 @@ var ts;
emitList(parentNode, typeArguments, 26896 /* TypeArguments */);
}
function emitTypeParameters(parentNode, typeParameters) {
- if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) {
+ if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
return emitTypeArguments(parentNode, parentNode.typeArguments);
}
emitList(parentNode, typeParameters, 26896 /* TypeParameters */);
@@ -73532,6 +73866,9 @@ var ts;
}
if (format & 7680 /* BracketsMask */) {
writePunctuation(getOpeningBracket(format));
+ if (isEmpty) {
+ emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
+ }
}
if (onBeforeEmitNodeArray) {
onBeforeEmitNodeArray(children);
@@ -73639,6 +73976,9 @@ var ts;
onAfterEmitNodeArray(children);
}
if (format & 7680 /* BracketsMask */) {
+ if (isEmpty) {
+ emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
+ }
writePunctuation(getClosingBracket(format));
}
}
@@ -74219,7 +74559,7 @@ var ts;
if (failed) {
return "";
}
- if (!commonPathComponents) {
+ if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
@@ -74351,8 +74691,7 @@ var ts;
}
ts.formatDiagnostics = formatDiagnostics;
function formatDiagnostic(diagnostic, host) {
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
+ var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
@@ -74377,8 +74716,9 @@ var ts;
var ellipsis = "...";
function getCategoryFormat(category) {
switch (category) {
- case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
+ case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
+ case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
}
}
@@ -74409,8 +74749,8 @@ var ts;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
- context += host.getNewLine();
for (var i = firstLine; i <= lastLine; i++) {
+ context += host.getNewLine();
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
@@ -74451,9 +74791,7 @@ var ts;
output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
output += " - ";
}
- var categoryColor = getCategoryFormat(diagnostic.category);
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- output += formatColorAndReset(category, categoryColor);
+ output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file) {
@@ -75606,6 +75944,7 @@ var ts;
if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
(imports || (imports = [])).push(node.arguments[0]);
}
+ // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) {
(imports || (imports = [])).push(node.arguments[0]);
}
@@ -75706,6 +76045,7 @@ var ts;
modulesWithElidedImports.set(file_1.path, false);
processImportedModules(file_1);
}
+ // See if we need to reprocess the imports due to prior skipped imports
else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
modulesWithElidedImports.set(file_1.path, false);
@@ -76044,7 +76384,7 @@ var ts;
// 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.sourceRoot || // there is --sourceRoot specified
- options.mapRoot) {
+ options.mapRoot) { // there is --mapRoot specified
// Precalculate and cache the common source directory
var dir = getCommonSourceDirectory();
// If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
@@ -76271,7 +76611,6 @@ var ts;
if (aug.kind === 9 /* StringLiteral */) {
res.push(aug.text);
}
- // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
}
return res;
}
@@ -77275,15 +77614,17 @@ var ts;
var filesWithChangedSetOfUnresolvedImports;
var filesWithInvalidatedResolutions;
var allFilesHaveInvalidatedResolution = false;
+ var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); });
+ var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
// The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
// The key in the map is source file's path.
// The values are Map of resolutions with key being name lookedup.
var resolvedModuleNames = ts.createMap();
var perDirectoryResolvedModuleNames = ts.createMap();
+ var nonRelaticeModuleNameCache = ts.createMap();
+ var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
var resolvedTypeReferenceDirectives = ts.createMap();
var perDirectoryResolvedTypeReferenceDirectives = ts.createMap();
- var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); });
- var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
/**
* 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
@@ -77356,6 +77697,7 @@ var ts;
}
function clearPerDirectoryResolutions() {
perDirectoryResolvedModuleNames.clear();
+ nonRelaticeModuleNameCache.clear();
perDirectoryResolvedTypeReferenceDirectives.clear();
}
function finishCachingPerDirectoryResolution() {
@@ -77369,7 +77711,7 @@ var ts;
clearPerDirectoryResolutions();
}
function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host);
+ var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache);
// return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
if (!resolutionHost.getGlobalCache) {
return primaryResult;
@@ -77415,15 +77757,8 @@ var ts;
perDirectoryResolution.set(name, resolution);
}
resolutionsInFile.set(name, resolution);
- if (resolution.failedLookupLocations) {
- if (existingResolution && existingResolution.failedLookupLocations) {
- watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution);
- }
- else {
- watchFailedLookupLocationOfResolution(resolution, 0);
- }
- }
- else if (existingResolution) {
+ watchFailedLookupLocationOfResolution(resolution);
+ if (existingResolution) {
stopWatchFailedLookupLocationOfResolution(existingResolution);
}
if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
@@ -77530,78 +77865,91 @@ var ts;
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
}
- function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) {
- var failedLookupLocations = resolution.failedLookupLocations;
- var existingFailedLookupLocations = existingResolution.failedLookupLocations;
- for (var index = 0; index < failedLookupLocations.length; index++) {
- if (index === existingFailedLookupLocations.length) {
- // Additional failed lookup locations, watch from this index
- watchFailedLookupLocationOfResolution(resolution, index);
- return;
- }
- else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) {
- // Different failed lookup locations,
- // Watch new resolution failed lookup locations from this index and
- // stop watching existing resolutions from this index
- watchFailedLookupLocationOfResolution(resolution, index);
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index);
- return;
- }
+ function watchFailedLookupLocationOfResolution(resolution) {
+ // No need to set the resolution refCount
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- // All new failed lookup locations are already watched (and are same),
- // Stop watching failed lookup locations of existing resolution after failed lookup locations length
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length);
- }
- function watchFailedLookupLocationOfResolution(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ if (resolution.refCount !== undefined) {
+ resolution.refCount++;
+ return;
+ }
+ resolution.refCount = 1;
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var setAtRoot = false;
+ for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- // If the failed lookup location path is not one of the supported extensions,
- // store it in the custom path
- if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
- customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
- }
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore;
if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- if (dirWatcher) {
- dirWatcher.refCount++;
+ // If the failed lookup location path is not one of the supported extensions,
+ // store it in the custom path
+ if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
+ }
+ if (dirPath === rootPath) {
+ setAtRoot = true;
}
else {
- directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ setDirectoryWatcher(dir, dirPath);
}
}
}
+ if (setAtRoot) {
+ setDirectoryWatcher(rootDir, rootPath);
+ }
+ }
+ function setDirectoryWatcher(dir, dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (dirWatcher) {
+ dirWatcher.refCount++;
+ }
+ else {
+ directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ }
}
function stopWatchFailedLookupLocationOfResolution(resolution) {
- if (resolution.failedLookupLocations) {
- stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0);
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- }
- function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ resolution.refCount--;
+ if (resolution.refCount) {
+ return;
+ }
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var removeAtRoot = false;
+ for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
- if (refCount) {
- if (refCount === 1) {
- customFailedLookupPaths.delete(failedLookupLocationPath);
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
+ if (!ignore) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
+ if (refCount) {
+ if (refCount === 1) {
+ customFailedLookupPaths.delete(failedLookupLocationPath);
+ }
+ else {
+ ts.Debug.assert(refCount > 1);
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ }
+ }
+ if (dirPath === rootPath) {
+ removeAtRoot = true;
}
else {
- ts.Debug.assert(refCount > 1);
- customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ removeDirectoryWatcher(dirPath);
}
}
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore;
- if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- // Do not close the watcher yet since it might be needed by other failed lookup locations.
- dirWatcher.refCount--;
- }
}
+ if (removeAtRoot) {
+ removeDirectoryWatcher(rootPath);
+ }
+ }
+ function removeDirectoryWatcher(dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ // Do not close the watcher yet since it might be needed by other failed lookup locations.
+ dirWatcher.refCount--;
}
function createDirectoryWatcher(directory, dirPath) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
@@ -77802,6 +78150,7 @@ var ts;
ts.createDiagnosticReporter = createDiagnosticReporter;
function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
if (system.clearScreen &&
+ !options.preserveWatchOutput &&
diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code &&
!options.extendedDiagnostics &&
!options.diagnostics) {
@@ -78276,6 +78625,9 @@ var ts;
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
}
else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
+ if (hostSourceFileInfo.fileWatcher) {
+ hostSourceFileInfo.fileWatcher.close();
+ }
sourceFilesCache.delete(oldSourceFile.path);
resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
}
@@ -78495,6 +78847,13 @@ var ts;
category: ts.Diagnostics.Command_line_Options,
description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
},
+ {
+ name: "preserveWatchOutput",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
+ },
{
name: "watch",
shortName: "w",
@@ -78576,9 +78935,10 @@ var ts;
"es2017.string": "lib.es2017.string.d.ts",
"es2017.intl": "lib.es2017.intl.d.ts",
"es2017.typedarrays": "lib.es2017.typedarrays.d.ts",
+ "es2018.promise": "lib.es2018.promise.d.ts",
+ "es2018.regexp": "lib.es2018.regexp.d.ts",
"esnext.array": "lib.esnext.array.d.ts",
"esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
- "esnext.promise": "lib.esnext.promise.d.ts",
}),
},
showInSimplifiedHelpView: true,
@@ -80446,7 +80806,7 @@ var ts;
for (var key in opts) {
if (opts.hasOwnProperty(key)) {
var type = getOptionFromName(key);
- if (type !== undefined) {
+ if (type !== undefined) { // Ignore unknown options
out[key] = getOptionValueWithEmptyStrings(opts[key], type);
}
}
@@ -80456,11 +80816,11 @@ var ts;
ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
function getOptionValueWithEmptyStrings(value, option) {
switch (option.type) {
- case "object":// "paths". Can't get any useful information from the value since we blank out strings, so just return "".
+ case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
return "";
- case "string":// Could be any arbitrary string -- use empty string instead.
+ case "string": // Could be any arbitrary string -- use empty string instead.
return "";
- case "number":// Allow numbers, but be sure to check it's actually a number.
+ case "number": // Allow numbers, but be sure to check it's actually a number.
return typeof value === "number" ? value : "";
case "boolean":
return typeof value === "boolean" ? value : "";
@@ -80896,16 +81256,13 @@ var ts;
}
ts.getTargetLabel = getTargetLabel;
function isJumpStatementTarget(node) {
- return node.kind === 71 /* Identifier */ &&
- (node.parent.kind === 222 /* BreakStatement */ || node.parent.kind === 221 /* ContinueStatement */) &&
- node.parent.label === node;
+ return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node;
}
ts.isJumpStatementTarget = isJumpStatementTarget;
function isLabelOfLabeledStatement(node) {
- return node.kind === 71 /* Identifier */ &&
- node.parent.kind === 226 /* LabeledStatement */ &&
- node.parent.label === node;
+ return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node;
}
+ ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement;
function isLabelName(node) {
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
@@ -81271,12 +81628,7 @@ var ts;
// be parented by the container of the SyntaxList, not the SyntaxList itself.
// In order to find the list item index, we first need to locate SyntaxList itself and then search
// for the position of the relevant node (or comma).
- var syntaxList = ts.forEach(node.parent.getChildren(), function (c) {
- // find syntax list that covers the span of the node
- if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) {
- return c;
- }
- });
+ var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); });
// Either we didn't find an appropriate list, or the list must contain us.
ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node));
return syntaxList;
@@ -82031,7 +82383,7 @@ var ts;
}
function suppressTrailing(node) {
ts.addEmitFlags(node, 1024 /* NoTrailingComments */);
- var lastChild = undefined;
+ var lastChild;
ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) {
// As an optimization, jump straight to the end of the list.
if (children.length) {
@@ -82258,7 +82610,7 @@ var ts;
case 13 /* NoSubstitutionTemplateLiteral */:
return 4 /* InTemplateHeadOrNoSubstitutionTemplate */;
default:
- throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
+ return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
}
}
return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined;
@@ -82365,7 +82717,7 @@ var ts;
case 0 /* None */:
return { prefix: "" };
default:
- throw ts.Debug.assertNever(lexState);
+ return ts.Debug.assertNever(lexState);
}
}
function isBinaryExpressionOperatorToken(token) {
@@ -83212,7 +83564,7 @@ var ts;
try {
typeRoots = ts.getEffectiveTypeRoots(options, host);
}
- catch (_b) { }
+ catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ }
if (typeRoots) {
for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) {
var root = typeRoots_2[_c];
@@ -83360,7 +83712,7 @@ var ts;
try {
return ts.directoryProbablyExists(path, host);
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return undefined;
}
function tryIOAndConsumeErrors(host, toApply) {
@@ -83371,7 +83723,7 @@ var ts;
try {
return toApply && toApply.apply(host, args);
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return undefined;
}
})(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {}));
@@ -83422,7 +83774,7 @@ var ts;
case 3 /* JsDocParameterName */:
return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag));
default:
- throw ts.Debug.assertNever(completionData);
+ return ts.Debug.assertNever(completionData);
}
}
Completions.getCompletionsAtPosition = getCompletionsAtPosition;
@@ -83459,7 +83811,7 @@ var ts;
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
}
function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) {
- var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
+ var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
if (sourceFile.languageVariant === 1 /* JSX */ && 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.
@@ -83494,7 +83846,7 @@ var ts;
if (keywordFilters !== 0 /* None */ || !isMemberCompletion) {
ts.addRange(entries, getKeywordCompletions(keywordFilters));
}
- return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
+ return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
}
function isMemberCompletionKind(kind) {
switch (kind) {
@@ -83843,7 +84195,6 @@ var ts;
var CompletionKind;
(function (CompletionKind) {
CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration";
- /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */
CompletionKind[CompletionKind["Global"] = 1] = "Global";
CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess";
CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike";
@@ -83930,6 +84281,7 @@ var ts;
var insideComment = ts.isInComment(sourceFile, position, currentToken);
log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
var insideJsDocTagTypeExpression = false;
+ var isInSnippetScope = false;
if (insideComment) {
if (ts.hasDocComment(sourceFile, position)) {
if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
@@ -84103,7 +84455,7 @@ var ts;
getTypeScriptMemberSymbols();
}
else if (isRightOfOpenTag) {
- var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNames(), "getJsxIntrinsicTagNames() should all be defined");
+ var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
if (tryGetGlobalSymbols()) {
symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 2097152 /* Alias */)); }));
}
@@ -84130,7 +84482,7 @@ var ts;
}
log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart));
var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, position, sourceFile, typeChecker);
- return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
+ return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
case 287 /* JSDocParameterTag */:
@@ -84240,7 +84592,7 @@ var ts;
keywordFilters = 3 /* FunctionLikeBodyKeywords */;
}
// Get all entities in the current scope.
- completionKind = 5 /* None */;
+ completionKind = 1 /* Global */;
isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
if (previousToken !== contextToken) {
ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
@@ -84274,9 +84626,7 @@ var ts;
previousToken.getStart() :
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
- if (isGlobalCompletionScope(scopeNode)) {
- completionKind = 1 /* Global */;
- }
+ isInSnippetScope = isSnippetScope(scopeNode);
var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
@@ -84296,7 +84646,7 @@ var ts;
filterGlobalCompletion(symbols);
return true;
}
- function isGlobalCompletionScope(scopeNode) {
+ function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
case 272 /* SourceFile */:
case 200 /* TemplateExpression */:
@@ -84472,7 +84822,7 @@ var ts;
|| containingNodeKind === 159 /* IndexSignature */ // [ | : string ]
|| containingNodeKind === 146 /* ComputedPropertyName */; // [ | /* this can become an index signature */
case 129 /* ModuleKeyword */: // module |
- case 130 /* NamespaceKeyword */:// namespace |
+ case 130 /* NamespaceKeyword */: // namespace |
return true;
case 23 /* DotToken */:
return containingNodeKind === 237 /* ModuleDeclaration */; // module A.|
@@ -84547,7 +84897,7 @@ var ts;
isNewIdentifierLocation = false;
var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
if (!ts.isVariableLike(rootDeclaration))
- throw ts.Debug.fail("Root declaration is not variable-like.");
+ return ts.Debug.fail("Root declaration is not variable-like.");
// We don't want to complete using the type acquired by the shape
// of the binding pattern; we are only interested in types acquired
// through type declaration or inference.
@@ -84667,7 +85017,7 @@ var ts;
if (contextToken) {
switch (contextToken.kind) {
case 17 /* OpenBraceToken */: // const x = { |
- case 26 /* CommaToken */:// const x = { a: 0, |
+ case 26 /* CommaToken */: // const x = { a: 0, |
var parent = contextToken.parent;
if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) {
return parent;
@@ -84685,7 +85035,7 @@ var ts;
if (contextToken) {
switch (contextToken.kind) {
case 17 /* OpenBraceToken */: // import { |
- case 26 /* CommaToken */:// import { a as 0, |
+ case 26 /* CommaToken */: // import { a as 0, |
switch (contextToken.parent.kind) {
case 245 /* NamedImports */:
case 249 /* NamedExports */:
@@ -84713,7 +85063,7 @@ var ts;
function tryGetClassLikeCompletionContainer(contextToken) {
if (contextToken) {
switch (contextToken.kind) {
- case 17 /* OpenBraceToken */:// class c { |
+ case 17 /* OpenBraceToken */: // class c { |
if (ts.isClassLike(contextToken.parent)) {
return contextToken.parent;
}
@@ -84914,7 +85264,7 @@ var ts;
case 110 /* LetKeyword */:
case 76 /* ConstKeyword */:
case 116 /* YieldKeyword */:
- case 139 /* TypeKeyword */:// type htm|
+ case 139 /* TypeKeyword */: // type htm|
return true;
}
// If the previous token is keyword correspoding to class member completion keyword
@@ -85029,7 +85379,7 @@ var ts;
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
var name = ts.getNameOfDeclaration(m);
- existingName = ts.getEscapedTextOfIdentifierOrLiteral(name);
+ existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
existingMemberNames.set(existingName, true);
}
@@ -85133,10 +85483,10 @@ var ts;
// TODO: GH#18169
return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
case 2 /* PropertyAccess */:
- case 5 /* None */:
case 1 /* Global */:
// Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547
return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true };
+ case 5 /* None */:
case 4 /* String */:
return validIdentiferResult;
default:
@@ -85309,30 +85659,17 @@ var ts;
}
function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken);
- return referenceEntries && convertReferencedSymbols(referenceEntries);
- }
- function convertReferencedSymbols(referenceEntries) {
- var fileNameToDocumentHighlights = ts.createMap();
- for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
- var entry = referenceEntries_1[_i];
- var _a = ts.FindAllReferences.toHighlightSpan(entry), fileName = _a.fileName, span_12 = _a.span;
- var highlightSpans = fileNameToDocumentHighlights.get(fileName);
- if (!highlightSpans) {
- fileNameToDocumentHighlights.set(fileName, highlightSpans = []);
- }
- highlightSpans.push(span_12);
- }
- return ts.arrayFrom(fileNameToDocumentHighlights.entries(), function (_a) {
+ 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) {
var fileName = _a[0], highlightSpans = _a[1];
return ({ fileName: fileName, highlightSpans: highlightSpans });
});
}
function getSyntacticDocumentHighlights(node, sourceFile) {
var highlightSpans = getHighlightSpans(node, sourceFile);
- if (!highlightSpans || highlightSpans.length === 0) {
- return undefined;
- }
- return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
+ return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
}
function getHighlightSpans(node, sourceFile) {
switch (node.kind) {
@@ -85873,7 +86210,9 @@ var ts;
}
else if (ts.isDefaultImport(direct)) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(direct);
- addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports
+ if (!isAvailableThroughGlobal) {
+ addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports
+ }
directImports.push(direct);
}
else {
@@ -86025,7 +86364,7 @@ var ts;
if (propertyName) {
// This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference.
singleReferences.push(propertyName);
- if (!isForRename) {
+ if (!isForRename) { // If renaming `foo`, don't touch `bar`, just `foo`.
// Search locally for `bar`.
addSearch(name, checker.getSymbolAtLocation(name));
}
@@ -86200,12 +86539,15 @@ var ts;
return exportInfo(symbol, getExportKindForDeclaration(exportNode));
}
}
+ // If we are in `export = a;` or `export default a;`, `parent` is the export assignment.
else if (ts.isExportAssignment(parent)) {
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(parent.parent)) {
return getExportAssignmentExport(parent.parent);
}
+ // Similar for `module.exports =` and `exports.A =`.
else if (ts.isBinaryExpression(parent)) {
return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true);
}
@@ -86276,10 +86618,10 @@ var ts;
return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol));
}
var decl = importedSymbol.valueDeclaration;
- if (ts.isExportAssignment(decl)) {
+ if (ts.isExportAssignment(decl)) { // `export = class {}`
return ts.Debug.assertDefined(decl.expression.symbol);
}
- else if (ts.isBinaryExpression(decl)) {
+ else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}`
return ts.Debug.assertDefined(decl.right.symbol);
}
return ts.Debug.fail();
@@ -86356,8 +86698,8 @@ var ts;
if (parent.kind === 272 /* SourceFile */) {
return parent;
}
- ts.Debug.assert(parent.kind === 238 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent));
- return parent.parent;
+ ts.Debug.assert(parent.kind === 238 /* ModuleBlock */);
+ return ts.cast(parent.parent, isAmbientModuleDeclaration);
}
function isAmbientModuleDeclaration(node) {
return node.kind === 237 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */;
@@ -86379,12 +86721,13 @@ var ts;
}
FindAllReferences.nodeEntry = nodeEntry;
function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
- var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position);
+ var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, /*options*/ {});
var checker = program.getTypeChecker();
return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) {
var definition = _a.definition, references = _a.references;
// Only include referenced symbols that have a valid definition.
- return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) };
+ return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) };
});
}
FindAllReferences.findReferencedSymbols = findReferencedSymbols;
@@ -86420,8 +86763,8 @@ var ts;
}
}
function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) {
- var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options));
- return ts.map(x, toReferenceEntry);
+ var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry);
}
FindAllReferences.findReferencedEntries = findReferencedEntries;
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) {
@@ -86429,46 +86772,41 @@ var ts;
return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options));
}
FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode;
- function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) {
- var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
- return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options);
- }
function flattenEntries(referenceSymbols) {
return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
}
- function definitionToReferencedSymbolDefinitionInfo(def, checker) {
+ function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
var info = (function () {
switch (def.type) {
case "symbol": {
- var symbol = def.symbol, node_3 = def.node;
- var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
+ var symbol = def.symbol;
+ var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
var name_4 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 };
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 };
}
case "label": {
- var node_4 = def.node;
- return { node: node_4, name: node_4.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_4.text, ts.SymbolDisplayPartKind.text)] };
+ var node_3 = def.node;
+ return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
}
case "keyword": {
- var node_5 = def.node;
- var name_5 = ts.tokenToString(node_5.kind);
- return { node: node_5, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ var node_4 = def.node;
+ var name_5 = ts.tokenToString(node_4.kind);
+ return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
}
case "this": {
- var node_6 = def.node;
- var symbol = checker.getSymbolAtLocation(node_6);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_6.getSourceFile(), ts.getContainerNode(node_6), node_6).displayParts;
- return { node: node_6, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
+ var node_5 = def.node;
+ var symbol = checker.getSymbolAtLocation(node_5);
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts;
+ return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
case "string": {
- var node_7 = def.node;
- return { node: node_7, name: node_7.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_7), ts.SymbolDisplayPartKind.stringLiteral)] };
+ var node_6 = def.node;
+ return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
}
+ default:
+ return ts.Debug.assertNever(def);
}
})();
- if (!info) {
- return undefined;
- }
var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts;
var sourceFile = node.getSourceFile();
return {
@@ -86481,8 +86819,10 @@ var ts;
displayParts: displayParts
};
}
- function getDefinitionKindAndDisplayParts(symbol, node, checker) {
- var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
+ function getDefinitionKindAndDisplayParts(symbol, checker, node) {
+ var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol);
+ var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node;
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
return { displayParts: displayParts, kind: symbolKind };
}
function toReferenceEntry(entry) {
@@ -86513,7 +86853,7 @@ var ts;
function implementationKindDisplayParts(node, checker) {
var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node);
if (symbol) {
- return getDefinitionKindAndDisplayParts(symbol, node, checker);
+ return getDefinitionKindAndDisplayParts(symbol, checker, node);
}
else if (node.kind === 182 /* ObjectLiteralExpression */) {
return {
@@ -86638,10 +86978,7 @@ var ts;
ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
- return [{
- definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration },
- references: references
- }];
+ return [{ definition: { type: "symbol", symbol: symbol }, references: references }];
}
/** getReferencedSymbols for special node kinds. */
function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
@@ -86649,17 +86986,15 @@ var ts;
return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken);
}
// Labels
- if (ts.isLabelName(node)) {
- if (ts.isJumpStatementTarget(node)) {
- var labelDefinition = ts.getTargetLabel(node.parent, node.text);
- // if we have a label definition, look within its statement for references, if not, then
- // the label is undefined and we have no results..
- return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
- }
- else {
- // it is a label definition and not a target, search within the parent labeledStatement
- return getLabelReferencesInNode(node.parent, node);
- }
+ if (ts.isJumpStatementTarget(node)) {
+ var labelDefinition = ts.getTargetLabel(node.parent, node.text);
+ // if we have a label definition, look within its statement for references, if not, then
+ // the label is undefined and we have no results..
+ return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
+ }
+ else if (ts.isLabelOfLabeledStatement(node)) {
+ // it is a label definition and not a target, search within the parent labeledStatement
+ return getLabelReferencesInNode(node.parent, node);
}
if (ts.isThis(node)) {
return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
@@ -86673,11 +87008,11 @@ var ts;
function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) {
symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
// Compute the meaning from the location and the symbol it references
- var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations);
+ var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol);
var result = [];
var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result);
if (node.kind === 79 /* DefaultKeyword */) {
- addReference(node, symbol, node, state);
+ addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
else {
@@ -86781,7 +87116,11 @@ var ts;
this.symbolIdToReferences = [];
// Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
this.sourceFileToSeenSymbols = [];
+ this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; });
}
+ State.prototype.includesSourceFile = function (sourceFile) {
+ return this.includedSourceFiles.has(sourceFile.fileName);
+ };
/** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
State.prototype.getImportSearches = function (exportSymbol, exportInfo) {
if (!this.importTracker)
@@ -86795,11 +87134,11 @@ var ts;
// Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`.
// The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form
// here appears to be intentional).
- var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b;
+ var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, allSearchSymbols = searchOptions.allSearchSymbols;
var escapedText = ts.escapeLeadingUnderscores(text);
var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
return {
- location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents,
+ symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents,
includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; },
};
};
@@ -86807,12 +87146,12 @@ var ts;
* Callback to add references for a particular searched symbol.
* This initializes a reference group, so only call this if you will add at least one reference.
*/
- State.prototype.referenceAdder = function (searchSymbol, searchLocation) {
+ State.prototype.referenceAdder = function (searchSymbol) {
var symbolId = ts.getSymbolId(searchSymbol);
var references = this.symbolIdToReferences[symbolId];
if (!references) {
references = this.symbolIdToReferences[symbolId] = [];
- this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references });
+ this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references });
}
return function (node) { return references.push(FindAllReferences.nodeEntry(node)); };
};
@@ -86837,7 +87176,7 @@ var ts;
var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers;
// For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file.
if (singleReferences.length) {
- var addRef = state.referenceAdder(exportSymbol, exportLocation);
+ var addRef = state.referenceAdder(exportSymbol);
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
addRef(singleRef);
@@ -86873,7 +87212,10 @@ var ts;
function searchForImportedSymbol(symbol, state) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- getReferencesInSourceFile(declaration.getSourceFile(), state.createSearch(declaration, symbol, 0 /* Import */), state);
+ var exportingFile = declaration.getSourceFile();
+ if (state.includesSourceFile(exportingFile)) {
+ getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state);
+ }
}
}
/** Search for all occurences of an identifier in a source file (and filter out the ones that match). */
@@ -86973,6 +87315,17 @@ var ts;
// So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.)
return exposedByParent ? scope.getSourceFile() : scope;
}
+ /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
+ function isSymbolReferencedInFile(definition, checker, sourceFile) {
+ var symbol = checker.getSymbolAtLocation(definition);
+ if (!symbol)
+ return true; // Be lenient with invalid code.
+ return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) {
+ var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), ts.isIdentifier);
+ return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol;
+ });
+ }
+ Core.isSymbolReferencedInFile = isSymbolReferencedInFile;
function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) {
if (container === void 0) { container = sourceFile; }
var positions = [];
@@ -87003,18 +87356,13 @@ var ts;
return positions;
}
function getLabelReferencesInNode(container, targetLabel) {
- var references = [];
var sourceFile = container.getSourceFile();
var labelName = targetLabel.text;
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container);
- for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) {
- var position = possiblePositions_1[_i];
+ var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) {
var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
// Only pick labels that are either the target label, or have a target that is the target label
- if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) {
- references.push(FindAllReferences.nodeEntry(node));
- }
- }
+ return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined;
+ });
return [{ definition: { type: "label", node: targetLabel }, references: references }];
}
function isValidReferencePosition(node, searchSymbolName) {
@@ -87034,24 +87382,15 @@ var ts;
}
}
function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) {
- var references = [];
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
+ var references = ts.flatMap(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references);
- }
+ return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) {
+ var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined;
+ });
+ });
return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined;
}
- function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) {
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile);
- for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) {
- var position = possiblePositions_2[_i];
- var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
- if (referenceLocation.kind === kind) {
- references.push(FindAllReferences.nodeEntry(referenceLocation));
- }
- }
- }
function getReferencesInSourceFile(sourceFile, search, state) {
state.cancellationToken.throwIfCancellationRequested();
return getReferencesInContainer(sourceFile, sourceFile, search, state);
@@ -87109,7 +87448,7 @@ var ts;
}
switch (state.specialSearchKind) {
case 0 /* None */:
- addReference(referenceLocation, relatedSymbol, search.location, state);
+ addReference(referenceLocation, relatedSymbol, state);
break;
case 1 /* Constructor */:
addConstructorReferences(referenceLocation, sourceFile, search, state);
@@ -87139,7 +87478,7 @@ var ts;
addRef();
}
if (!state.options.isForRename && state.markSeenReExportRHS(name)) {
- addReference(name, referenceSymbol, name, state);
+ addReference(name, referenceSymbol, state);
}
}
else {
@@ -87161,7 +87500,7 @@ var ts;
searchForImportedSymbol(imported, state);
}
function addRef() {
- addReference(referenceLocation, localSymbol, search.location, state);
+ addReference(referenceLocation, localSymbol, state);
}
}
function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
@@ -87206,11 +87545,11 @@ var ts;
* position of property accessing, the referenceEntry of such position will be handled in the first case.
*/
if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) {
- addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state);
+ addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state);
}
}
- function addReference(referenceLocation, relatedSymbol, searchLocation, state) {
- var addRef = state.referenceAdder(relatedSymbol, searchLocation);
+ function addReference(referenceLocation, relatedSymbol, state) {
+ var addRef = state.referenceAdder(relatedSymbol);
if (state.options.implementations) {
addImplementationReferences(referenceLocation, addRef, state);
}
@@ -87221,9 +87560,9 @@ var ts;
/** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */
function addConstructorReferences(referenceLocation, sourceFile, search, state) {
if (ts.isNewExpressionTarget(referenceLocation)) {
- addReference(referenceLocation, search.symbol, search.location, state);
+ addReference(referenceLocation, search.symbol, state);
}
- var pusher = function () { return state.referenceAdder(search.symbol, search.location); };
+ var pusher = function () { return state.referenceAdder(search.symbol); };
if (ts.isClassLike(referenceLocation.parent)) {
ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation);
// This is the class declaration containing the constructor.
@@ -87238,11 +87577,11 @@ var ts;
}
}
function addClassStaticThisReferences(referenceLocation, search, state) {
- addReference(referenceLocation, search.symbol, search.location, state);
- if (ts.isClassLike(referenceLocation.parent)) {
+ addReference(referenceLocation, search.symbol, state);
+ if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) {
ts.Debug.assert(referenceLocation.parent.name === referenceLocation);
// This is the class declaration.
- addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location));
+ addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol));
}
}
function addStaticThisReferences(classLike, pusher) {
@@ -87367,7 +87706,7 @@ var ts;
return result;
}
function getContainingTypeReference(node) {
- var topLevelTypeReference = undefined;
+ var topLevelTypeReference;
while (node) {
if (ts.isTypeNode(node)) {
topLevelTypeReference = node;
@@ -87495,24 +87834,19 @@ var ts;
default:
return undefined;
}
- var references = [];
var sourceFile = searchSpaceNode.getSourceFile();
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode);
- for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) {
- var position = possiblePositions_3[_i];
+ var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) {
var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
if (!node || node.kind !== 97 /* SuperKeyword */) {
- continue;
+ return;
}
var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false);
// If we have a 'super' container, we must have an enclosing class.
// Now make sure the owning class is the same as the search-space
// and has the same static qualifier as the original 'super's owner.
- if (container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) {
- references.push(FindAllReferences.nodeEntry(node));
- }
- }
- return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol, node: superKeyword }, references: references }];
+ return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined;
+ });
+ return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }];
}
function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false);
@@ -87547,18 +87881,11 @@ var ts;
return undefined;
}
var references = [];
- var possiblePositions;
- if (searchSpaceNode.kind === 272 /* SourceFile */) {
- ts.forEach(sourceFiles, function (sourceFile) {
- cancellationToken.throwIfCancellationRequested();
- possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this");
- getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, staticFlag, references);
- });
- }
- else {
- var sourceFile = searchSpaceNode.getSourceFile();
- possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode);
- getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, references);
+ for (var _i = 0, _a = searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ cancellationToken.throwIfCancellationRequested();
+ var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode);
+ getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFile : searchSpaceNode, positions, staticFlag, references);
}
return [{
definition: { type: "this", node: thisOrSuperKeyword },
@@ -87602,26 +87929,17 @@ var ts;
});
}
function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
- var references = [];
- for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
- var sourceFile = sourceFiles_7[_i];
+ var references = ts.flatMap(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text);
- getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references);
- }
+ return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) {
+ var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false), ts.isStringLiteral);
+ return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined;
+ });
+ });
return [{
definition: { type: "string", node: node },
references: references
}];
- function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) {
- for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) {
- var position = possiblePositions_4[_i];
- var node_8 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
- if (node_8 && node_8.kind === 9 /* StringLiteral */ && node_8.text === searchText) {
- references.push(FindAllReferences.nodeEntry(node_8, /*isInString*/ true));
- }
- }
- }
}
// For certain symbol kinds, we need to include other symbols in the search set.
// This is not needed when searching for re-exports.
@@ -87838,7 +88156,9 @@ var ts;
* module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module)
* do not intersect in any of the three spaces.
*/
- function getIntersectingMeaningFromDeclarations(meaning, declarations) {
+ function getIntersectingMeaningFromDeclarations(node, symbol) {
+ var meaning = ts.getMeaningFromLocation(node);
+ var declarations = symbol.declarations;
if (declarations) {
var lastIterationMeaning = void 0;
do {
@@ -87859,6 +88179,7 @@ var ts;
}
return meaning;
}
+ Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
function isImplementation(node) {
if (!node) {
return false;
@@ -87962,9 +88283,8 @@ var ts;
}
// Labels
if (ts.isJumpStatementTarget(node)) {
- var labelName = node.text;
- var label = ts.getTargetLabel(node.parent, labelName);
- return label ? [createDefinitionInfoFromName(label, "label" /* label */, labelName, /*containerName*/ undefined)] : undefined;
+ var label = ts.getTargetLabel(node.parent, node.text);
+ return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined;
}
var typeChecker = program.getTypeChecker();
var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
@@ -88903,7 +89223,7 @@ var ts;
case 6 /* NameContainsNonURISafeCharacters */:
return "Package name '" + typing + "' contains non URI safe characters";
case 0 /* Ok */:
- throw ts.Debug.fail(); // Shouldn't have called this.
+ return ts.Debug.fail(); // Shouldn't have called this.
default:
ts.Debug.assertNever(result);
}
@@ -88929,8 +89249,8 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) {
- var sourceFile = sourceFiles_8[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
_loop_8(sourceFile);
}
rawItems.sort(compareNavigateToItems);
@@ -88990,41 +89310,35 @@ var ts;
return true;
}
function tryAddSingleDeclarationName(declaration, containers) {
- if (declaration) {
- var name = ts.getNameOfDeclaration(declaration);
- if (name) {
- var text = ts.getTextOfIdentifierOrLiteral(name);
- if (text !== undefined) {
- containers.unshift(text);
- }
- else if (name.kind === 146 /* ComputedPropertyName */) {
- return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true);
- }
- else {
- // Don't know how to add this.
- return false;
- }
- }
+ var name = ts.getNameOfDeclaration(declaration);
+ if (name && ts.isPropertyNameLiteral(name)) {
+ containers.unshift(ts.getTextOfIdentifierOrLiteral(name));
+ return true;
+ }
+ else if (name && name.kind === 146 /* ComputedPropertyName */) {
+ return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true);
+ }
+ else {
+ // Don't know how to add this.
+ return false;
}
- return true;
}
// Only added the names of computed properties if they're simple dotted expressions, like:
//
// [X.Y.Z]() { }
function tryAddComputedPropertyName(expression, containers, includeLastPortion) {
- var text = ts.getTextOfIdentifierOrLiteral(expression);
- if (text !== undefined) {
+ if (ts.isPropertyNameLiteral(expression)) {
+ var text = ts.getTextOfIdentifierOrLiteral(expression);
if (includeLastPortion) {
containers.unshift(text);
}
return true;
}
- if (expression.kind === 183 /* PropertyAccessExpression */) {
- var propertyAccess = expression;
+ if (ts.isPropertyAccessExpression(expression)) {
if (includeLastPortion) {
- containers.unshift(propertyAccess.name.text);
+ containers.unshift(expression.name.text);
}
- return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true);
+ return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true);
}
return false;
}
@@ -89663,16 +89977,20 @@ var ts;
if (node.name && ts.getFullWidth(node.name) > 0) {
return ts.declarationNameToString(node.name);
}
+ // See if it is a var initializer. If so, use the var name.
else if (node.parent.kind === 230 /* VariableDeclaration */) {
return ts.declarationNameToString(node.parent.name);
}
+ // See if it is of the form " = function(){...}". If so, use the text from the left-hand side.
else if (node.parent.kind === 198 /* BinaryExpression */ &&
node.parent.operatorToken.kind === 58 /* EqualsToken */) {
return nodeText(node.parent.left).replace(whiteSpaceRegex, "");
}
+ // See if it is a property assignment, and if so use the property name
else if (node.parent.kind === 268 /* PropertyAssignment */ && node.parent.name) {
return nodeText(node.parent.name);
}
+ // Default exports are named "default"
else if (ts.getModifierFlags(node) & 512 /* Default */) {
return "default";
}
@@ -89697,44 +90015,102 @@ var ts;
(function (ts) {
var OrganizeImports;
(function (OrganizeImports) {
- function organizeImports(sourceFile, formatContext, host) {
- // TODO (https://github.com/Microsoft/TypeScript/issues/10020): sort *within* ambient modules (find using isAmbientModule)
- // All of the old ImportDeclarations in the file, in syntactic order.
- var oldImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
- if (oldImportDecls.length === 0) {
- return [];
- }
- var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
- var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) {
- return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier);
- });
- var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
- return getExternalModuleName(importGroup[0].moduleSpecifier)
- ? coalesceImports(removeUnusedImports(importGroup))
- : importGroup;
- });
+ /**
+ * Organize imports by:
+ * 1) Removing unused imports
+ * 2) Coalescing imports from the same module
+ * 3) Sorting imports
+ */
+ function organizeImports(sourceFile, formatContext, host, program) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
- // Delete or replace the first import.
- if (newImportDecls.length === 0) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[0]);
- }
- else {
- // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
- changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: false,
- useNonAdjustedEndPosition: false,
- suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
- });
- }
- // Delete any subsequent imports.
- for (var i = 1; i < oldImportDecls.length; i++) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
+ // All of the old ImportDeclarations in the file, in syntactic order.
+ var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
+ organizeImportsWorker(topLevelImportDecls);
+ for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
+ var ambientModule = _a[_i];
+ var ambientModuleBody = getModuleBlock(ambientModule);
+ var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
+ organizeImportsWorker(ambientModuleImportDecls);
}
return changeTracker.getChanges();
+ function organizeImportsWorker(oldImportDecls) {
+ if (ts.length(oldImportDecls) === 0) {
+ return;
+ }
+ var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
+ var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
+ var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
+ return getExternalModuleName(importGroup[0].moduleSpecifier)
+ ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
+ : importGroup;
+ });
+ // Delete or replace the first import.
+ if (newImportDecls.length === 0) {
+ changeTracker.deleteNode(sourceFile, oldImportDecls[0]);
+ }
+ else {
+ // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
+ changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
+ useNonAdjustedStartPosition: false,
+ useNonAdjustedEndPosition: false,
+ suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
+ });
+ }
+ // Delete any subsequent imports.
+ for (var i = 1; i < oldImportDecls.length; i++) {
+ changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
+ }
+ }
}
OrganizeImports.organizeImports = organizeImports;
- function removeUnusedImports(oldImports) {
- return oldImports; // TODO (https://github.com/Microsoft/TypeScript/issues/10020)
+ function getModuleBlock(moduleDecl) {
+ var body = moduleDecl.body;
+ return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body));
+ }
+ function removeUnusedImports(oldImports, sourceFile, program) {
+ var typeChecker = program.getTypeChecker();
+ var jsxNamespace = typeChecker.getJsxNamespace();
+ var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx;
+ var usedImports = [];
+ for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
+ var importDecl = oldImports_1[_i];
+ var importClause = importDecl.importClause;
+ if (!importClause) {
+ // Imports without import clauses are assumed to be included for their side effects and are not removed.
+ usedImports.push(importDecl);
+ continue;
+ }
+ var name = importClause.name, namedBindings = importClause.namedBindings;
+ // Default import
+ if (name && !isDeclarationUsed(name)) {
+ name = undefined;
+ }
+ if (namedBindings) {
+ if (ts.isNamespaceImport(namedBindings)) {
+ // Namespace import
+ if (!isDeclarationUsed(namedBindings.name)) {
+ namedBindings = undefined;
+ }
+ }
+ else {
+ // List of named imports
+ var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.propertyName || e.name); });
+ if (newElements.length < namedBindings.elements.length) {
+ namedBindings = newElements.length
+ ? ts.updateNamedImports(namedBindings, newElements)
+ : undefined;
+ }
+ }
+ }
+ if (name || namedBindings) {
+ usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
+ }
+ }
+ return usedImports;
+ function isDeclarationUsed(identifier) {
+ // The JSX factory symbol is always used.
+ return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
+ }
}
function getExternalModuleName(specifier) {
return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier)
@@ -89749,7 +90125,7 @@ var ts;
if (importGroup.length === 0) {
return importGroup;
}
- var _a = getImportParts(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports;
+ var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports;
var coalescedImports = [];
if (importWithoutClause) {
coalescedImports.push(importWithoutClause);
@@ -89758,15 +90134,17 @@ var ts;
// produce two import declarations in this special case.
if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
// Add the namespace import to the existing default ImportDeclaration.
- var defaultImportClause = defaultImports[0].parent;
- coalescedImports.push(updateImportDeclarationAndClause(defaultImportClause, defaultImportClause.name, namespaceImports[0]));
+ var defaultImport = defaultImports[0];
+ coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings));
return coalescedImports;
}
- var sortedNamespaceImports = ts.stableSort(namespaceImports, function (n1, n2) { return compareIdentifiers(n1.name, n2.name); });
+ var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) {
+ return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name);
+ });
for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) {
var namespaceImport = sortedNamespaceImports_1[_i];
// Drop the name, if any
- coalescedImports.push(updateImportDeclarationAndClause(namespaceImport.parent, /*name*/ undefined, namespaceImport));
+ coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings));
}
if (defaultImports.length === 0 && namedImports.length === 0) {
return coalescedImports;
@@ -89774,30 +90152,37 @@ var ts;
var newDefaultImport;
var newImportSpecifiers = [];
if (defaultImports.length === 1) {
- newDefaultImport = defaultImports[0];
+ newDefaultImport = defaultImports[0].importClause.name;
}
else {
for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) {
var defaultImport = defaultImports_1[_b];
- newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport));
+ newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name));
}
}
- newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (n) { return n.elements; }));
+ newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
- var importClause = defaultImports.length > 0
- ? defaultImports[0].parent
- : namedImports[0].parent;
+ var importDecl = defaultImports.length > 0
+ ? defaultImports[0]
+ : namedImports[0];
var newNamedImports = sortedImportSpecifiers.length === 0
? undefined
: namedImports.length === 0
? ts.createNamedImports(sortedImportSpecifiers)
- : ts.updateNamedImports(namedImports[0], sortedImportSpecifiers);
- coalescedImports.push(updateImportDeclarationAndClause(importClause, newDefaultImport, newNamedImports));
+ : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers);
+ coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports));
return coalescedImports;
- function getImportParts(importGroup) {
+ /*
+ * Returns entire import declarations because they may already have been rewritten and
+ * may lack parent pointers. The desired parts can easily be recovered based on the
+ * categorization.
+ *
+ * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`.
+ */
+ function getCategorizedImports(importGroup) {
var importWithoutClause;
var defaultImports = [];
var namespaceImports = [];
@@ -89812,14 +90197,14 @@ var ts;
}
var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
if (name) {
- defaultImports.push(name);
+ defaultImports.push(importDeclaration);
}
if (namedBindings) {
if (ts.isNamespaceImport(namedBindings)) {
- namespaceImports.push(namedBindings);
+ namespaceImports.push(importDeclaration);
}
else {
- namedImports.push(namedBindings);
+ namedImports.push(importDeclaration);
}
}
}
@@ -89833,12 +90218,11 @@ var ts;
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseSensitive(s1.text, s2.text);
}
- function updateImportDeclarationAndClause(importClause, name, namedBindings) {
- var importDeclaration = importClause.parent;
- return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, name, namedBindings), importDeclaration.moduleSpecifier);
- }
}
OrganizeImports.coalesceImports = coalesceImports;
+ function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
+ return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
+ }
/* internal */ // Exported for testing
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
@@ -89891,8 +90275,8 @@ var ts;
continue;
}
if (!result[1]) {
- var span_13 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span_13, span_13, /*autoCollapse*/ false, result[2] || "#region"));
+ var span_12 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
+ regions.push(createOutliningSpan(span_12, span_12, /*autoCollapse*/ false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -90131,10 +90515,10 @@ var ts;
// But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
var wordSpans = getWordSpans(candidate);
for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
- var span_14 = wordSpans_1[_i];
- if (partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ true)) {
+ var span_13 = wordSpans_1[_i];
+ if (partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ true)) {
return createPatternMatch(PatternMatchKind.substring, punctuationStripped,
- /*isCaseSensitive:*/ partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ false));
+ /*isCaseSensitive:*/ partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ false));
}
}
}
@@ -90236,7 +90620,7 @@ var ts;
//
// Only if all words have some sort of match is the pattern considered matched.
var subWordTextChunks = segment.subWordTextChunks;
- var matches = undefined;
+ var matches;
for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) {
var subWordTextChunk = subWordTextChunks_1[_i];
// Try to match the candidate with this word
@@ -90284,8 +90668,8 @@ var ts;
// and I will both match in UI.
var currentCandidate = 0;
var currentChunkSpan = 0;
- var firstMatch = undefined;
- var contiguous = undefined;
+ var firstMatch;
+ var contiguous;
while (true) {
// Let's consider our termination cases
if (currentChunkSpan === chunkCharacterSpans.length) {
@@ -90585,11 +90969,18 @@ var ts;
function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
if (readImportFiles === void 0) { readImportFiles = true; }
if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
- var referencedFiles = [];
- var typeReferenceDirectives = [];
+ var pragmaContext = {
+ languageVersion: 1 /* ES5 */,
+ pragmas: undefined,
+ checkJsDirective: undefined,
+ referencedFiles: [],
+ typeReferenceDirectives: [],
+ amdDependencies: [],
+ hasNoDefaultLib: undefined,
+ moduleName: undefined
+ };
var importedFiles = [];
var ambientExternalModules;
- var isNoDefaultLib = false;
var braceNesting = 0;
// assume that text represent an external module if it contains at least one top level import/export
// ambient modules that are found inside external modules are interpreted as module augmentations
@@ -90604,23 +90995,6 @@ var ts;
}
return token;
}
- function processTripleSlashDirectives() {
- var commentRanges = ts.getLeadingCommentRanges(sourceText, 0);
- ts.forEach(commentRanges, function (commentRange) {
- var comment = sourceText.substring(commentRange.pos, commentRange.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange);
- if (referencePathMatchResult) {
- isNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var fileReference = referencePathMatchResult.fileReference;
- if (fileReference) {
- var collection = referencePathMatchResult.isTypeReferenceDirective
- ? typeReferenceDirectives
- : referencedFiles;
- collection.push(fileReference);
- }
- }
- });
- }
function getFileReference() {
var fileName = ts.scanner.getTokenValue();
var pos = ts.scanner.getTokenPos();
@@ -90881,7 +91255,8 @@ var ts;
if (readImportFiles) {
processImports();
}
- processTripleSlashDirectives();
+ ts.processCommentPragmas(pragmaContext, sourceText);
+ ts.processPragmasIntoFields(pragmaContext, ts.noop);
if (externalModule) {
// for external modules module all nested ambient modules are augmentations
if (ambientExternalModules) {
@@ -90891,7 +91266,7 @@ var ts;
importedFiles.push(decl.ref);
}
}
- return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined };
+ return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined };
}
else {
// for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
@@ -90910,7 +91285,7 @@ var ts;
}
}
}
- return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames };
+ return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
}
}
ts.preProcessFile = preProcessFile;
@@ -90941,22 +91316,17 @@ var ts;
var symbol = typeChecker.getSymbolAtLocation(node);
// Only allow a symbol to be renamed if it actually has at least one declaration.
if (symbol) {
- var declarations = symbol.getDeclarations();
+ var declarations = symbol.declarations;
if (declarations && declarations.length > 0) {
// Disallow rename for elements that are defined in the standard TypeScript library.
- if (ts.some(declarations, isDefinedInLibraryFile)) {
+ if (declarations.some(isDefinedInLibraryFile)) {
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";
- if (node.kind === 71 /* Identifier */ &&
- node.originalKeywordKind === 79 /* DefaultKeyword */ &&
- symbol.parent.flags & 1536 /* Module */) {
+ if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) {
return undefined;
}
var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
- if (!kind) {
- return undefined;
- }
var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */)
? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
: undefined;
@@ -90965,12 +91335,11 @@ var ts;
return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
}
}
- else if (node.kind === 9 /* StringLiteral */) {
+ else if (ts.isStringLiteral(node)) {
if (isDefinedInLibraryFile(node)) {
return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
}
- var displayName = ts.stripQuotes(node.text);
- return getRenameInfoSuccess(displayName, displayName, "var" /* variableElement */, "" /* none */, node, sourceFile);
+ return getRenameInfoSuccess(node.text, node.text, "var" /* variableElement */, "" /* none */, node, sourceFile);
}
}
function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
@@ -91428,6 +91797,63 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ function computeSuggestionDiagnostics(sourceFile, program) {
+ program.getSemanticDiagnostics(sourceFile);
+ var checker = program.getDiagnosticsProducingTypeChecker();
+ var diags = [];
+ if (sourceFile.commonJsModuleIndicator) {
+ diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
+ }
+ var isJsFile = ts.isSourceFileJavaScript(sourceFile);
+ function check(node) {
+ switch (node.kind) {
+ case 232 /* FunctionDeclaration */:
+ case 190 /* FunctionExpression */:
+ if (isJsFile) {
+ var symbol = node.symbol;
+ if (symbol.members && (symbol.members.size > 0)) {
+ diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
+ }
+ }
+ break;
+ }
+ if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) {
+ diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
+ }
+ node.forEachChild(check);
+ }
+ check(sourceFile);
+ if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
+ for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
+ var importNode = _a[_i];
+ var name = importNameForConvertToDefaultImport(importNode.parent);
+ if (!name)
+ continue;
+ var module = ts.getResolvedModule(sourceFile, importNode.text);
+ var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
+ if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
+ diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
+ }
+ }
+ }
+ return diags.concat(checker.getSuggestionDiagnostics(sourceFile));
+ }
+ ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
+ function importNameForConvertToDefaultImport(node) {
+ if (ts.isExternalModuleReference(node)) {
+ return node.parent.name;
+ }
+ if (ts.isImportDeclaration(node)) {
+ var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier;
+ return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier)
+ ? importClause.namedBindings.name
+ : undefined;
+ }
+ }
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var SymbolDisplay;
(function (SymbolDisplay) {
@@ -91637,7 +92063,7 @@ var ts;
}
}
else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration
- (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) {
+ (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* 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
@@ -92915,7 +93341,7 @@ var ts;
// case SyntaxKind.ConstructorDeclaration:
// case SyntaxKind.SimpleArrowFunctionExpression:
// case SyntaxKind.ParenthesizedArrowFunctionExpression:
- case 234 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one
+ case 234 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one
return true;
}
return false;
@@ -94717,26 +95143,14 @@ var ts;
function isControlFlowEndingStatement(kind, parent) {
switch (kind) {
case 223 /* ReturnStatement */:
- case 227 /* ThrowStatement */:
- switch (parent.kind) {
- case 211 /* Block */:
- var grandParent = parent.parent;
- switch (grandParent && grandParent.kind) {
- case 232 /* FunctionDeclaration */:
- case 190 /* FunctionExpression */:
- // We may want to write inner functions after this.
- return false;
- default:
- return true;
- }
- case 264 /* CaseClause */:
- case 265 /* DefaultClause */:
- case 272 /* SourceFile */:
- case 238 /* ModuleBlock */:
- return true;
- default:
- throw ts.Debug.fail();
+ case 227 /* ThrowStatement */: {
+ if (parent.kind !== 211 /* Block */) {
+ return true;
}
+ var grandParent = parent.parent;
+ // In a function, we may want to write inner functions after this.
+ return !(grandParent && grandParent.kind === 190 /* FunctionExpression */ || grandParent.kind === 232 /* FunctionDeclaration */);
+ }
case 221 /* ContinueStatement */:
case 222 /* BreakStatement */:
return true;
@@ -94874,10 +95288,9 @@ var ts;
}
var ChangeTracker = /** @class */ (function () {
/** Public for tests only. Other callers should use `ChangeTracker.with`. */
- function ChangeTracker(newLineCharacter, formatContext, validator) {
+ function ChangeTracker(newLineCharacter, formatContext) {
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
- this.validator = validator;
this.changes = [];
this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
// Map from class id to nodes to insert at the start
@@ -95016,10 +95429,10 @@ var ts;
if (ts.isStatement(before) || ts.isClassElement(before)) {
return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
}
- else if (ts.isVariableDeclaration(before)) {
+ else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2;
return { suffix: ", " };
}
- throw ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
+ return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
};
ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
var firstStatement = ts.firstOrUndefined(ctr.body.statements);
@@ -95096,7 +95509,7 @@ var ts;
else if (ts.isVariableDeclaration(node)) {
return { prefix: ", " };
}
- throw ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it
+ return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it
};
/**
* This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
@@ -95247,92 +95660,83 @@ var ts;
_this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true });
});
};
- ChangeTracker.prototype.getChanges = function () {
- var _this = this;
+ /**
+ * Note: after calling this, the TextChanges object must be discarded!
+ * @param validate only for tests
+ * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions,
+ * so we can only call this once and can't get the non-formatted text separately.
+ */
+ ChangeTracker.prototype.getChanges = function (validate) {
this.finishInsertNodeAtClassStart();
- return ts.group(this.changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
- var sourceFile = changesInFile[0].sourceFile;
- var textChanges = ChangeTracker.normalize(changesInFile).map(function (c) {
- return ts.createTextChange(ts.createTextSpanFromRange(c.range), _this.computeNewText(c, sourceFile));
- });
- return { fileName: sourceFile.fileName, textChanges: textChanges };
- });
- };
- ChangeTracker.prototype.computeNewText = function (change, sourceFile) {
- var _this = this;
- if (change.kind === ChangeKind.Remove) {
- // deletion case
- return "";
- }
- var options = change.options || {};
- var text;
- var pos = change.range.pos;
- var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos;
- if (change.kind === ChangeKind.ReplaceWithMultipleNodes) {
- var lastIndex_1 = change.nodes.length - 1;
- var parts = change.nodes.map(function (n, index) {
- var formatted = _this.getFormattedTextOfNode(n, sourceFile, pos, options);
- return index === lastIndex_1 || ts.endsWith(formatted, _this.newLineCharacter)
- ? formatted
- : (formatted + _this.newLineCharacter);
- });
- text = parts.join("");
- }
- else {
- ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode");
- text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options);
- }
- // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
- text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, "");
- return (options.prefix || "") + text + (options.suffix || "");
- };
- ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) {
- var nonformattedText = getNonformattedText(node, sourceFile, this.newLineCharacter);
- if (this.validator) {
- this.validator(nonformattedText);
- }
- var formatOptions = this.formatContext.options;
- var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos;
- var initialIndentation = options.indentation !== undefined
- ? options.indentation
- : (options.useIndentationFromFile !== false)
- ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter))
- : 0;
- var delta = options.delta !== undefined
- ? options.delta
- : ts.formatting.SmartIndenter.shouldIndentChildNode(node)
- ? (formatOptions.indentSize || 0)
- : 0;
- return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.formatContext);
- };
- ChangeTracker.normalize = function (changes) {
- // order changes by start position
- var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; });
- // verify that change intervals do not overlap, except possibly at end points.
- for (var i = 0; i < normalized.length - 2; i++) {
- ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos);
- }
- return normalized;
+ return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
};
return ChangeTracker;
}());
textChanges_1.ChangeTracker = ChangeTracker;
- function getNonformattedText(node, sourceFile, newLine) {
- var writer = new Writer(newLine);
- var printer = ts.createPrinter({ newLine: newLine === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */ }, writer);
- printer.writeNode(4 /* Unspecified */, node, sourceFile, writer);
- return { text: writer.getText(), node: assignPositionsToNode(node) };
- }
- function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, formatContext) {
- var lineMap = ts.computeLineStarts(nonFormattedText.text);
- var file = {
- text: nonFormattedText.text,
- lineMap: lineMap,
- getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); }
- };
- var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext);
- return applyChanges(nonFormattedText.text, changes);
- }
+ var changesToText;
+ (function (changesToText) {
+ function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
+ return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
+ var sourceFile = changesInFile[0].sourceFile;
+ // order changes by start position
+ var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
+ var _loop_10 = 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 - 2; i++) {
+ _loop_10(i);
+ }
+ var textChanges = normalized.map(function (c) {
+ return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
+ });
+ return { fileName: sourceFile.fileName, textChanges: textChanges };
+ });
+ }
+ changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
+ if (change.kind === ChangeKind.Remove) {
+ return "";
+ }
+ var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos;
+ var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); };
+ var text = change.kind === ChangeKind.ReplaceWithMultipleNodes
+ ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter)
+ : format(change.node);
+ // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
+ var noIndent = (options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, "");
+ return (options.prefix || "") + noIndent + (options.suffix || "");
+ }
+ /** Note: this may mutate `nodeIn`. */
+ function getFormattedTextOfNode(nodeIn, sourceFile, pos, options, newLineCharacter, formatContext, validate) {
+ var _a = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _a.node, text = _a.text;
+ if (validate)
+ validate(node, text);
+ var formatOptions = formatContext.options;
+ var initialIndentation = options.indentation !== undefined
+ ? options.indentation
+ : (options.useIndentationFromFile !== false)
+ ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, options.prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos)
+ : 0;
+ var delta = options.delta !== undefined
+ ? options.delta
+ : ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn)
+ ? (formatOptions.indentSize || 0)
+ : 0;
+ var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } };
+ var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext);
+ return applyChanges(text, changes);
+ }
+ /** Note: output node may be mutated input node. */
+ function getNonformattedText(node, sourceFile, newLineCharacter) {
+ var writer = new Writer(newLineCharacter);
+ var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */;
+ ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer);
+ return { text: writer.getText(), node: assignPositionsToNode(node) };
+ }
+ })(changesToText || (changesToText = {}));
function applyChanges(text, changes) {
for (var i = changes.length - 1; i >= 0; i--) {
var change = changes[i];
@@ -95611,7 +96015,7 @@ var ts;
codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges;
function eachDiagnostic(_a, errorCodes, cb) {
var program = _a.program, sourceFile = _a.sourceFile;
- for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) {
+ for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) {
var diag = _b[_i];
if (ts.contains(errorCodes, diag.code)) {
cb(diag);
@@ -95677,6 +96081,831 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "annotateWithTypeFromJSDoc";
+ var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var decl = getDeclaration(context.sourceFile, context.span.start);
+ if (!decl)
+ return;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Annotate_with_type_from_JSDoc);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); });
+ return [{ description: description, changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var decl = getDeclaration(diag.file, diag.start);
+ if (decl)
+ doChange(changes, diag.file, decl);
+ }); },
+ });
+ function getDeclaration(file, pos) {
+ var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false);
+ // For an arrow function with no name, 'name' lands on the first parameter.
+ return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
+ }
+ function parameterShouldGetTypeFromJSDoc(node) {
+ return isDeclarationWithType(node) && hasUsableJSDoc(node);
+ }
+ codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc;
+ function hasUsableJSDoc(decl) {
+ return ts.isFunctionLikeDeclaration(decl)
+ ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl))
+ : !decl.type && !!ts.getJSDocType(decl);
+ }
+ function doChange(changes, sourceFile, decl) {
+ if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
+ ts.findAncestor(decl, ts.isFunctionLike);
+ var fn = ts.findAncestor(decl, ts.isFunctionLikeDeclaration);
+ var functionWithType = addTypesToFunctionLike(fn);
+ ts.suppressLeadingAndTrailingTrivia(functionWithType);
+ changes.replaceNode(sourceFile, fn, functionWithType, ts.textChanges.useNonAdjustedPositions);
+ return;
+ }
+ else {
+ var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix
+ ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix.
+ var declarationWithType = addType(decl, transformJSDocType(jsdocType));
+ ts.suppressLeadingAndTrailingTrivia(declarationWithType);
+ changes.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions);
+ }
+ }
+ function isDeclarationWithType(node) {
+ return ts.isFunctionLikeDeclaration(node) ||
+ node.kind === 230 /* VariableDeclaration */ ||
+ node.kind === 150 /* PropertySignature */ ||
+ node.kind === 151 /* PropertyDeclaration */;
+ }
+ function addTypesToFunctionLike(decl) {
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, /*checkJSDoc*/ true);
+ var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, /*checkJSDoc*/ true)), p.initializer); });
+ var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, /*checkJSDoc*/ true));
+ switch (decl.kind) {
+ case 232 /* FunctionDeclaration */:
+ return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
+ case 154 /* Constructor */:
+ return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body);
+ case 190 /* FunctionExpression */:
+ return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
+ case 191 /* ArrowFunction */:
+ return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body);
+ case 153 /* MethodDeclaration */:
+ return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body);
+ case 155 /* GetAccessor */:
+ return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body);
+ case 156 /* SetAccessor */:
+ return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body);
+ default:
+ return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind);
+ }
+ }
+ function addType(decl, jsdocType) {
+ switch (decl.kind) {
+ case 230 /* VariableDeclaration */:
+ return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer);
+ case 150 /* PropertySignature */:
+ return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
+ case 151 /* PropertyDeclaration */:
+ return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
+ default:
+ return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind);
+ }
+ }
+ function transformJSDocType(node) {
+ if (node === undefined) {
+ return undefined;
+ }
+ switch (node.kind) {
+ case 275 /* JSDocAllType */:
+ case 276 /* JSDocUnknownType */:
+ return ts.createTypeReferenceNode("any", ts.emptyArray);
+ case 279 /* JSDocOptionalType */:
+ return transformJSDocOptionalType(node);
+ case 278 /* JSDocNonNullableType */:
+ return transformJSDocType(node.type);
+ case 277 /* JSDocNullableType */:
+ return transformJSDocNullableType(node);
+ case 281 /* JSDocVariadicType */:
+ return transformJSDocVariadicType(node);
+ case 280 /* JSDocFunctionType */:
+ return transformJSDocFunctionType(node);
+ case 148 /* Parameter */:
+ return transformJSDocParameter(node);
+ case 161 /* TypeReference */:
+ return transformJSDocTypeReference(node);
+ default:
+ var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined);
+ ts.setEmitFlags(visited, 1 /* SingleLine */);
+ return visited;
+ }
+ }
+ function transformJSDocOptionalType(node) {
+ return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
+ }
+ function transformJSDocNullableType(node) {
+ return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
+ }
+ function transformJSDocVariadicType(node) {
+ return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
+ }
+ function transformJSDocFunctionType(node) {
+ var parameters = node.parameters && node.parameters.map(transformJSDocType);
+ return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type);
+ }
+ function transformJSDocParameter(node) {
+ var index = node.parent.parameters.indexOf(node);
+ var isRest = node.type.kind === 281 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
+ var name = node.name || (isRest ? "rest" : "arg" + index);
+ var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
+ return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
+ }
+ function transformJSDocTypeReference(node) {
+ var name = node.typeName;
+ var args = node.typeArguments;
+ if (ts.isIdentifier(node.typeName)) {
+ if (ts.isJSDocIndexSignature(node)) {
+ return transformJSDocIndexSignature(node);
+ }
+ var text = node.typeName.text;
+ switch (node.typeName.text) {
+ case "String":
+ case "Boolean":
+ case "Object":
+ case "Number":
+ text = text.toLowerCase();
+ break;
+ case "array":
+ case "date":
+ case "promise":
+ text = text[0].toUpperCase() + text.slice(1);
+ break;
+ }
+ name = ts.createIdentifier(text);
+ if ((text === "Array" || text === "Promise") && !node.typeArguments) {
+ args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
+ }
+ else {
+ args = ts.visitNodes(node.typeArguments, transformJSDocType);
+ }
+ }
+ return ts.createTypeReferenceNode(name, args);
+ }
+ function transformJSDocIndexSignature(node) {
+ var index = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s",
+ /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []),
+ /*initializer*/ undefined);
+ var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
+ ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
+ return indexSignature;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "convertFunctionToEs6Class";
+ var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
+ return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_function_to_an_ES2015_class), changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
+ });
+ function doChange(changes, sourceFile, position, checker) {
+ var deletedNodes = [];
+ var deletes = [];
+ var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false));
+ if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
+ // Bad input
+ return undefined;
+ }
+ var ctorDeclaration = ctorSymbol.valueDeclaration;
+ var precedingNode;
+ var newClassDeclaration;
+ switch (ctorDeclaration.kind) {
+ case 232 /* FunctionDeclaration */:
+ precedingNode = ctorDeclaration;
+ deleteNode(ctorDeclaration);
+ newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
+ break;
+ case 230 /* VariableDeclaration */:
+ precedingNode = ctorDeclaration.parent.parent;
+ if (ctorDeclaration.parent.declarations.length === 1) {
+ deleteNode(precedingNode);
+ }
+ else {
+ deleteNode(ctorDeclaration, /*inList*/ true);
+ }
+ newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
+ break;
+ }
+ if (!newClassDeclaration) {
+ return undefined;
+ }
+ // Because the preceding node could be touched, we need to insert nodes before delete nodes.
+ changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
+ for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) {
+ var deleteCallback = deletes_1[_i];
+ deleteCallback();
+ }
+ function deleteNode(node, inList) {
+ if (inList === void 0) { inList = false; }
+ if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) {
+ // Parent node has already been deleted; do nothing
+ return;
+ }
+ deletedNodes.push(node);
+ if (inList) {
+ deletes.push(function () { return changes.deleteNodeInList(sourceFile, node); });
+ }
+ else {
+ deletes.push(function () { return changes.deleteNode(sourceFile, node); });
+ }
+ }
+ function createClassElementsFromSymbol(symbol) {
+ var memberElements = [];
+ // all instance members are stored in the "member" array of symbol
+ if (symbol.members) {
+ symbol.members.forEach(function (member) {
+ var memberElement = createClassElement(member, /*modifiers*/ undefined);
+ if (memberElement) {
+ memberElements.push(memberElement);
+ }
+ });
+ }
+ // all static members are stored in the "exports" array of symbol
+ if (symbol.exports) {
+ symbol.exports.forEach(function (member) {
+ var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]);
+ if (memberElement) {
+ memberElements.push(memberElement);
+ }
+ });
+ }
+ return memberElements;
+ function shouldConvertDeclaration(_target, source) {
+ // Right now the only thing we can convert are function expressions - other values shouldn't get
+ // transformed. We can update this once ES public class properties are available.
+ return ts.isFunctionLike(source);
+ }
+ function createClassElement(symbol, modifiers) {
+ // both properties and methods are bound as property symbols
+ if (!(symbol.flags & 4 /* Property */)) {
+ return;
+ }
+ var memberDeclaration = symbol.valueDeclaration;
+ var assignmentBinaryExpression = memberDeclaration.parent;
+ if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
+ return;
+ }
+ // 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 === 214 /* ExpressionStatement */
+ ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
+ deleteNode(nodeToDelete);
+ if (!assignmentBinaryExpression.right) {
+ return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
+ /*type*/ undefined, /*initializer*/ undefined);
+ }
+ switch (assignmentBinaryExpression.right.kind) {
+ case 190 /* FunctionExpression */: {
+ var functionExpression = assignmentBinaryExpression.right;
+ var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */));
+ var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
+ /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
+ copyComments(assignmentBinaryExpression, method, sourceFile);
+ return method;
+ }
+ case 191 /* ArrowFunction */: {
+ var arrowFunction = assignmentBinaryExpression.right;
+ var arrowFunctionBody = arrowFunction.body;
+ var bodyBlock = void 0;
+ // case 1: () => { return [1,2,3] }
+ if (arrowFunctionBody.kind === 211 /* Block */) {
+ bodyBlock = arrowFunctionBody;
+ }
+ // case 2: () => [1,2,3]
+ else {
+ bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
+ }
+ var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */));
+ var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
+ /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
+ copyComments(assignmentBinaryExpression, method, sourceFile);
+ return method;
+ }
+ default: {
+ // Don't try to declare members in JavaScript files
+ if (ts.isSourceFileJavaScript(sourceFile)) {
+ return;
+ }
+ var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
+ /*type*/ undefined, assignmentBinaryExpression.right);
+ copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ return prop;
+ }
+ }
+ }
+ }
+ function createClassFromVariableDeclaration(node) {
+ var initializer = node.initializer;
+ if (!initializer || initializer.kind !== 190 /* FunctionExpression */) {
+ return undefined;
+ }
+ if (node.name.kind !== 71 /* Identifier */) {
+ return undefined;
+ }
+ var memberElements = createClassElementsFromSymbol(initializer.symbol);
+ if (initializer.body) {
+ memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
+ }
+ var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */);
+ var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
+ /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
+ // Don't call copyComments here because we'll already leave them in place
+ return cls;
+ }
+ function createClassFromFunctionDeclaration(node) {
+ var memberElements = createClassElementsFromSymbol(ctorSymbol);
+ if (node.body) {
+ memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
+ }
+ var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */);
+ var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
+ /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
+ // Don't call copyComments here because we'll already leave them in place
+ return cls;
+ }
+ }
+ function copyComments(sourceNode, targetNode, sourceFile) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ if (kind === 3 /* MultiLineCommentTrivia */) {
+ // Remove leading /*
+ pos += 2;
+ // Remove trailing */
+ end -= 2;
+ }
+ else {
+ // Remove leading //
+ pos += 2;
+ }
+ ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl);
+ });
+ }
+ function getModifierKindFromSource(source, kind) {
+ return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code],
+ getCodeActions: function (context) {
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module);
+ var sourceFile = context.sourceFile, program = context.program;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
+ var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target);
+ if (moduleExportsChangedToDefault) {
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var importingFile = _a[_i];
+ fixImportOfModuleExports(importingFile, sourceFile, changes);
+ }
+ }
+ });
+ // No support for fix-all since this applies to the whole file at once anyway.
+ return [{ description: description, changes: changes, fixId: undefined }];
+ },
+ });
+ function fixImportOfModuleExports(importingFile, exportingFile, changes) {
+ for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
+ var moduleSpecifier = _a[_i];
+ var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
+ if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
+ continue;
+ }
+ var parent = moduleSpecifier.parent;
+ switch (parent.kind) {
+ case 252 /* ExternalModuleReference */: {
+ var importEq = parent.parent;
+ changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text));
+ break;
+ }
+ case 185 /* CallExpression */: {
+ var call = parent;
+ if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) {
+ changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default"));
+ }
+ break;
+ }
+ }
+ }
+ }
+ /** @returns Whether we converted a `module.exports =` to a default export. */
+ function convertFileToEs6Module(sourceFile, checker, changes, target) {
+ var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
+ var exports = collectExportRenames(sourceFile, checker, identifiers);
+ convertExportsAccesses(sourceFile, exports, changes);
+ var moduleExportsChangedToDefault = false;
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports);
+ moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
+ }
+ return moduleExportsChangedToDefault;
+ }
+ function collectExportRenames(sourceFile, checker, identifiers) {
+ var res = ts.createMap();
+ forEachExportReference(sourceFile, function (node) {
+ var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
+ if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
+ || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) {
+ // Unconditionally add an underscore in case `text` is a keyword.
+ res.set(text, makeUniqueName("_" + text, identifiers));
+ }
+ });
+ return res;
+ }
+ function convertExportsAccesses(sourceFile, exports, changes) {
+ forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
+ if (isAssignmentLhs) {
+ return;
+ }
+ var text = node.name.text;
+ changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
+ });
+ }
+ function forEachExportReference(sourceFile, cb) {
+ sourceFile.forEachChild(function recur(node) {
+ if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
+ var parent = node.parent;
+ cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */);
+ }
+ node.forEachChild(recur);
+ });
+ }
+ function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) {
+ switch (statement.kind) {
+ case 212 /* VariableStatement */:
+ convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target);
+ return false;
+ case 214 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ switch (expression.kind) {
+ case 185 /* CallExpression */: {
+ if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) {
+ // For side-effecting require() call, just make a side-effecting import.
+ changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text));
+ }
+ return false;
+ }
+ case 198 /* BinaryExpression */: {
+ var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
+ return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports);
+ }
+ }
+ }
+ // falls through
+ default:
+ return false;
+ }
+ }
+ function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) {
+ var declarationList = statement.declarationList;
+ var foundImport = false;
+ var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
+ var name = decl.name, initializer = decl.initializer;
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
+ // `const alias = module.exports;` can be removed.
+ foundImport = true;
+ return [];
+ }
+ if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) {
+ foundImport = true;
+ return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target);
+ }
+ else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) {
+ foundImport = true;
+ return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers);
+ }
+ else {
+ // Move it out to its own variable statement.
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
+ }
+ });
+ if (foundImport) {
+ // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ }
+ }
+ /** Converts `const name = require("moduleSpecifier").propertyName` */
+ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) {
+ switch (name.kind) {
+ case 178 /* ObjectBindingPattern */:
+ case 179 /* ArrayBindingPattern */: {
+ // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
+ var tmp = makeUniqueName(propertyName, identifiers);
+ return [
+ makeSingleImport(tmp, propertyName, moduleSpecifier),
+ makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
+ ];
+ }
+ case 71 /* Identifier */:
+ // `const a = require("b").c` --> `import { c as a } from "./b";
+ return [makeSingleImport(name.text, propertyName, moduleSpecifier)];
+ default:
+ ts.Debug.assertNever(name);
+ }
+ }
+ function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) {
+ if (!ts.isPropertyAccessExpression(left)) {
+ return false;
+ }
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
+ // `const alias = module.exports;` or `module.exports = alias;` can be removed.
+ changes.deleteNode(sourceFile, statement);
+ }
+ else {
+ var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
+ var changedToDefaultExport = false;
+ if (!newNodes) {
+ (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ }
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ return changedToDefaultExport;
+ }
+ }
+ else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
+ convertNamedExport(sourceFile, statement, left.name, right, changes, exports);
+ }
+ return false;
+ var _a;
+ }
+ /**
+ * Convert `module.exports = { ... }` to individual exports..
+ * We can't always do this if the module has interesting members -- then it will be a default export instead.
+ */
+ function tryChangeModuleExportsObject(object) {
+ return ts.mapAllOrFail(object.properties, function (prop) {
+ switch (prop.kind) {
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
+ case 269 /* ShorthandPropertyAssignment */:
+ case 270 /* SpreadAssignment */:
+ return undefined;
+ case 268 /* PropertyAssignment */:
+ return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer);
+ case 153 /* MethodDeclaration */:
+ return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop);
+ default:
+ ts.Debug.assertNever(prop);
+ }
+ });
+ }
+ function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) {
+ // If "originalKeywordKind" was set, this is e.g. `exports.
+ var text = propertyName.text;
+ var rename = exports.get(text);
+ if (rename !== undefined) {
+ /*
+ const _class = 0;
+ export { _class as class };
+ */
+ var newNodes = [
+ makeConst(/*modifiers*/ undefined, rename, right),
+ makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
+ ];
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ }
+ else {
+ changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true });
+ }
+ }
+ function convertModuleExportsToExportDefault(exported, checker) {
+ var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
+ switch (exported.kind) {
+ case 190 /* FunctionExpression */:
+ case 191 /* ArrowFunction */: {
+ // `module.exports = function f() {}` --> `export default function f() {}`
+ var fn = exported;
+ return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
+ }
+ case 203 /* ClassExpression */: {
+ // `module.exports = class C {}` --> `export default class C {}`
+ var cls = exported;
+ return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
+ }
+ case 185 /* CallExpression */:
+ if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) {
+ return convertReExportAll(exported.arguments[0], checker);
+ }
+ // falls through
+ default:
+ // `module.exports = 0;` --> `export default 0;`
+ return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
+ }
+ }
+ function convertReExportAll(reExported, checker) {
+ // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
+ var moduleSpecifier = reExported.text;
+ var moduleSymbol = checker.getSymbolAtLocation(reExported);
+ var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
+ return exports.has("export=")
+ ? [[reExportDefault(moduleSpecifier)], true]
+ : !exports.has("default")
+ ? [[reExportStar(moduleSpecifier)], false]
+ // If there's some non-default export, must include both `export *` and `export default`.
+ : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
+ }
+ function reExportStar(moduleSpecifier) {
+ return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
+ }
+ function reExportDefault(moduleSpecifier) {
+ return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
+ }
+ function convertExportsDotXEquals(name, exported) {
+ var modifiers = [ts.createToken(84 /* ExportKeyword */)];
+ switch (exported.kind) {
+ case 190 /* FunctionExpression */: {
+ var expressionName = exported.name;
+ if (expressionName && expressionName.text !== name) {
+ // `exports.f = function g() {}` -> `export const f = function g() {}`
+ return exportConst();
+ }
+ }
+ // falls through
+ case 191 /* ArrowFunction */:
+ // `exports.f = function() {}` --> `export function f() {}`
+ return functionExpressionToDeclaration(name, modifiers, exported);
+ case 203 /* ClassExpression */:
+ // `exports.C = class {}` --> `export class C {}`
+ return classExpressionToDeclaration(name, modifiers, exported);
+ default:
+ return exportConst();
+ }
+ function exportConst() {
+ // `exports.x = 0;` --> `export const x = 0;`
+ return makeConst(modifiers, ts.createIdentifier(name), exported);
+ }
+ }
+ /**
+ * Converts `const <> = require("x");`.
+ * Returns nodes that will replace the variable declaration for the commonjs import.
+ * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
+ */
+ function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) {
+ switch (name.kind) {
+ case 178 /* 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
+ : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
+ });
+ if (importSpecifiers) {
+ return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
+ }
+ }
+ // falls through -- object destructuring has an interesting pattern and must be a variable declaration
+ case 179 /* ArrayBindingPattern */: {
+ /*
+ import x from "x";
+ const [a, b, c] = x;
+ */
+ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers);
+ return [
+ makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
+ makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
+ ];
+ }
+ case 71 /* Identifier */:
+ return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers);
+ default:
+ ts.Debug.assertNever(name);
+ }
+ }
+ /**
+ * Convert `import x = require("x").`
+ * Also converts uses like `x.y()` to `y()` and uses a named import.
+ */
+ function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) {
+ var nameSymbol = checker.getSymbolAtLocation(name);
+ // Maps from module property name to name actually used. (The same if there isn't shadowing.)
+ var namedBindingsNames = ts.createMap();
+ // True if there is some non-property use like `x()` or `f(x)`.
+ var needDefaultImport = false;
+ for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
+ var use = _a[_i];
+ if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
+ // This was a use of a different symbol with the same name, due to shadowing. Ignore.
+ continue;
+ }
+ var parent = use.parent;
+ if (ts.isPropertyAccessExpression(parent)) {
+ var expression = parent.expression, propertyName = parent.name.text;
+ ts.Debug.assert(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);
+ }
+ changes.replaceNode(file, parent, ts.createIdentifier(idName));
+ }
+ else {
+ needDefaultImport = true;
+ }
+ }
+ var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
+ var propertyName = _a[0], idName = _a[1];
+ return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
+ }));
+ if (!namedBindings) {
+ // If it was unused, ensure that we at least import *something*.
+ needDefaultImport = true;
+ }
+ return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ }
+ // Identifiers helpers
+ function makeUniqueName(name, identifiers) {
+ while (identifiers.original.has(name) || identifiers.additional.has(name)) {
+ name = "_" + name;
+ }
+ identifiers.additional.set(name, true);
+ return name;
+ }
+ function collectFreeIdentifiers(file) {
+ var map = ts.createMultiMap();
+ file.forEachChild(function recur(node) {
+ if (ts.isIdentifier(node) && isFreeIdentifier(node)) {
+ map.add(node.text, node);
+ }
+ node.forEachChild(recur);
+ });
+ return map;
+ }
+ function isFreeIdentifier(node) {
+ var parent = node.parent;
+ switch (parent.kind) {
+ case 183 /* PropertyAccessExpression */:
+ return parent.name !== node;
+ case 180 /* BindingElement */:
+ return parent.propertyName !== node;
+ default:
+ return true;
+ }
+ }
+ // Node helpers
+ function functionExpressionToDeclaration(name, additionalModifiers, fn) {
+ return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
+ ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
+ }
+ function classExpressionToDeclaration(name, additionalModifiers, cls) {
+ return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
+ ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
+ }
+ function makeSingleImport(localName, propertyName, moduleSpecifier) {
+ return propertyName === "default"
+ ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
+ : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ }
+ function makeImport(name, namedImports, moduleSpecifier) {
+ return makeImportDeclaration(name, namedImports, ts.createLiteral(moduleSpecifier));
+ }
+ function makeImportDeclaration(name, namedImports, moduleSpecifier) {
+ var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
+ return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier);
+ }
+ codefix.makeImportDeclaration = makeImportDeclaration;
+ function makeImportSpecifier(propertyName, name) {
+ return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
+ }
+ function makeConst(modifiers, name, init) {
+ return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
+ }
+ function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
+ return ts.createExportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -95749,9 +96978,7 @@ var ts;
},
});
function getClass(sourceFile, pos) {
- var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false));
- ts.Debug.assert(!!classDeclaration);
- return classDeclaration;
+ return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)));
}
function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) {
// Note that this is ultimately derived from a map indexed by symbol names,
@@ -96059,7 +97286,6 @@ var ts;
commands: [getCommand(fileName, packageName)],
};
}
- codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes;
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
@@ -96082,17 +97308,21 @@ var ts;
return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }];
},
fixIds: [fixId],
- getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
- addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes);
- }); },
+ getAllCodeActions: function (context) {
+ var seenClassDeclarations = ts.createMap();
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var classDeclaration = getClass(diag.file, diag.start);
+ if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
+ addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes);
+ }
+ });
+ },
});
function getClass(sourceFile, pos) {
- // This is the identifier in the case of a class declaration
+ // Token is the identifier in the case of a class declaration
// or the class keyword token in the case of a class expression.
var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
- var classDeclaration = token.parent;
- ts.Debug.assert(ts.isClassLike(classDeclaration));
- return classDeclaration;
+ return ts.cast(token.parent, ts.isClassLike);
}
function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) {
var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration);
@@ -96432,9 +97662,9 @@ var ts;
changes.deleteNodeInList(sourceFile, parent);
}
break;
- case 243 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *'
+ case 243 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *'
var importClause = parent;
- if (!importClause.namedBindings) {
+ if (!importClause.namedBindings) { // |import d from './file'|
changes.deleteNode(sourceFile, ts.getAncestor(importClause, 242 /* ImportDeclaration */));
}
else {
@@ -96800,7 +98030,7 @@ var ts;
case 252 /* ExternalModuleReference */:
return parent.parent;
case 248 /* ExportDeclaration */:
- case 185 /* CallExpression */:// For "require()" calls
+ case 185 /* CallExpression */: // For "require()" calls
// Ignore these, can't add imports to them.
return undefined;
default:
@@ -97219,7 +98449,7 @@ var ts;
var parent = token.parent;
var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent);
if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258 /* JsxOpeningFragment */) {
- umdSymbol = checker.resolveName(checker.getJsxNamespace(), isNodeOpeningLikeElement ? parent.tagName : parent, 107455 /* Value */, /*excludeGlobals*/ false);
+ umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 107455 /* Value */, /*excludeGlobals*/ false);
}
}
if (ts.isUMDExportSymbol(umdSymbol)) {
@@ -97249,7 +98479,7 @@ var ts;
// Fall back to the `import * as ns` style import.
return 2 /* Namespace */;
default:
- throw ts.Debug.assertNever(moduleKind);
+ return ts.Debug.assertNever(moduleKind);
}
}
function getActionsForNonUMDImport(context) {
@@ -97719,7 +98949,7 @@ var ts;
case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, program, cancellationToken) : undefined;
default:
- throw ts.Debug.fail(String(errorCode));
+ return ts.Debug.fail(String(errorCode));
}
}
function isAllowedTokenKind(kind) {
@@ -97889,13 +99119,13 @@ var ts;
var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
return callContexts && declaration.parameters.map(function (parameter, parameterIndex) {
var types = [];
- var isRestParameter = ts.isRestParameter(parameter);
+ var isRest = ts.isRestParameter(parameter);
for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) {
var callContext = callContexts_1[_i];
if (callContext.argumentTypes.length <= parameterIndex) {
continue;
}
- if (isRestParameter) {
+ if (isRest) {
for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) {
types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i]));
}
@@ -97908,7 +99138,7 @@ var ts;
return undefined;
}
var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */));
- return isRestParameter ? checker.createArrayType(type) : type;
+ return isRest ? checker.createArrayType(type) : type;
});
}
InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences;
@@ -97965,6 +99195,8 @@ var ts;
case 37 /* PlusToken */:
usageContext.isNumberOrString = true;
break;
+ // case SyntaxKind.ExclamationToken:
+ // no inferences here;
}
}
function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) {
@@ -98230,9 +99462,7 @@ var ts;
var opts = context.program.getCompilerOptions();
var variations = [];
// import Bluebird from "bluebird";
- variations.push(createAction(context, sourceFile, node, ts.createImportDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
@@ -98281,7 +99511,171 @@ var ts;
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
+ var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
+ var fixIdAddInitializer = "addMissingPropertyInitializer";
+ var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start);
+ if (!propertyDeclaration)
+ return;
+ var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
+ var result = [
+ getActionForAddMissingUndefinedType(context, propertyDeclaration),
+ getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter)
+ ];
+ ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter));
+ return result;
+ },
+ fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
+ getAllCodeActions: function (context) {
+ var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start);
+ if (!propertyDeclaration)
+ return;
+ switch (context.fixId) {
+ case fixIdAddDefiniteAssignmentAssertions:
+ addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration, newLineCharacter);
+ break;
+ case fixIdAddUndefinedType:
+ addUndefinedType(changes, diag.file, propertyDeclaration);
+ break;
+ case fixIdAddInitializer:
+ var checker = context.program.getTypeChecker();
+ var initializer = getInitializer(checker, propertyDeclaration);
+ if (!initializer)
+ return;
+ addInitializer(changes, diag.file, propertyDeclaration, initializer, newLineCharacter);
+ break;
+ default:
+ ts.Debug.fail(JSON.stringify(context.fixId));
+ }
+ });
+ },
+ });
+ function getPropertyDeclaration(sourceFile, pos) {
+ var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined;
+ }
+ function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter) {
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_definite_assignment_assertion_to_property_0), [propertyDeclaration.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration, newLineCharacter); });
+ return { description: description, changes: changes, fixId: fixIdAddDefiniteAssignmentAssertions };
+ }
+ function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, newLineCharacter) {
+ var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer);
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter });
+ }
+ function getActionForAddMissingUndefinedType(context, propertyDeclaration) {
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_undefined_type_to_property_0), [propertyDeclaration.name.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); });
+ return { description: description, changes: changes, fixId: fixIdAddUndefinedType };
+ }
+ function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
+ var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */);
+ var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode];
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types));
+ }
+ function getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter) {
+ var checker = context.program.getTypeChecker();
+ var initializer = getInitializer(checker, propertyDeclaration);
+ if (!initializer)
+ return undefined;
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_initializer_to_property_0), [propertyDeclaration.name.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer, newLineCharacter); });
+ return { description: description, changes: changes, fixId: fixIdAddInitializer };
+ }
+ function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer, newLineCharacter) {
+ var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer);
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter });
+ }
+ function getInitializer(checker, propertyDeclaration) {
+ return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type));
+ }
+ function getDefaultValueFromType(checker, type) {
+ if (type.flags & 2 /* String */) {
+ return ts.createLiteral("");
+ }
+ else if (type.flags & 4 /* Number */) {
+ return ts.createNumericLiteral("0");
+ }
+ else if (type.flags & 8 /* Boolean */) {
+ return ts.createFalse();
+ }
+ else if (type.flags & 224 /* Literal */) {
+ return ts.createLiteral(type.value);
+ }
+ else if (type.flags & 131072 /* Union */) {
+ return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); });
+ }
+ else if (ts.getObjectFlags(type) & 1 /* Class */) {
+ var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
+ if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */))
+ return undefined;
+ var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; });
+ if (constructorDeclaration && constructorDeclaration.parameters.length)
+ return undefined;
+ return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
+ }
+ return undefined;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "useDefaultImport";
+ var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, start = context.span.start;
+ var info = getInfo(sourceFile, start);
+ if (!info)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
+ return [{ description: description, changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var info = getInfo(diag.file, diag.start);
+ if (info)
+ doChange(changes, diag.file, info);
+ }); },
+ });
+ function getInfo(sourceFile, pos) {
+ var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ if (!ts.isIdentifier(name))
+ return undefined; // bad input
+ var parent = name.parent;
+ if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) {
+ return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression };
+ }
+ else if (ts.isNamespaceImport(parent)) {
+ var importNode = parent.parent.parent;
+ return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier };
+ }
+ }
+ function doChange(changes, sourceFile, info) {
+ changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
///
+///
+///
+///
///
///
///
@@ -98300,960 +99694,8 @@ var ts;
///
///
///
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var annotateWithTypeFromJSDoc;
- (function (annotateWithTypeFromJSDoc) {
- var refactorName = "Annotate with type from JSDoc";
- var actionName = "annotate";
- var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (ts.isInJavaScriptFile(context.file)) {
- return undefined;
- }
- var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false);
- if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) {
- return [{
- name: refactorName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName
- }
- ]
- }];
- }
- }
- function hasUsableJSDoc(decl) {
- if (!decl) {
- return false;
- }
- if (ts.isFunctionLikeDeclaration(decl)) {
- return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl));
- }
- return !decl.type && !!ts.getJSDocType(decl);
- }
- function getEditsForAction(context, action) {
- if (actionName !== action) {
- return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action);
- }
- var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false);
- var decl = ts.findAncestor(node, isDeclarationWithType);
- if (!decl || decl.type) {
- return undefined;
- }
- var jsdocType = ts.getJSDocType(decl);
- var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }));
- if (isFunctionWithJSDoc || jsdocType && decl.kind === 148 /* Parameter */) {
- return getEditsForFunctionAnnotation(context);
- }
- else if (jsdocType) {
- return getEditsForAnnotation(context);
- }
- else {
- ts.Debug.assert(!!refactor, "No applicable refactor found.");
- }
- }
- function getEditsForAnnotation(context) {
- var sourceFile = context.file;
- var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false);
- var decl = ts.findAncestor(token, isDeclarationWithType);
- var jsdocType = ts.getJSDocType(decl);
- if (!decl || !jsdocType || decl.type) {
- return ts.Debug.fail("!decl || !jsdocType || decl.type: !" + decl + " || !" + jsdocType + " || " + decl.type);
- }
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var declarationWithType = addType(decl, transformJSDocType(jsdocType));
- ts.suppressLeadingAndTrailingTrivia(declarationWithType);
- changeTracker.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions);
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined
- };
- }
- function getEditsForFunctionAnnotation(context) {
- var sourceFile = context.file;
- var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false);
- var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration);
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var functionWithType = addTypesToFunctionLike(decl);
- ts.suppressLeadingAndTrailingTrivia(functionWithType);
- changeTracker.replaceNode(sourceFile, decl, functionWithType, ts.textChanges.useNonAdjustedPositions);
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined
- };
- }
- function isDeclarationWithType(node) {
- return ts.isFunctionLikeDeclaration(node) ||
- node.kind === 230 /* VariableDeclaration */ ||
- node.kind === 148 /* Parameter */ ||
- node.kind === 150 /* PropertySignature */ ||
- node.kind === 151 /* PropertyDeclaration */;
- }
- function addTypesToFunctionLike(decl) {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, /*checkJSDoc*/ true);
- var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, /*checkJSDoc*/ true)), p.initializer); });
- var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, /*checkJSDoc*/ true));
- switch (decl.kind) {
- case 232 /* FunctionDeclaration */:
- return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
- case 154 /* Constructor */:
- return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body);
- case 190 /* FunctionExpression */:
- return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
- case 191 /* ArrowFunction */:
- return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body);
- case 153 /* MethodDeclaration */:
- return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body);
- case 155 /* GetAccessor */:
- return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body);
- case 156 /* SetAccessor */:
- return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body);
- default:
- return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind);
- }
- }
- function addType(decl, jsdocType) {
- switch (decl.kind) {
- case 230 /* VariableDeclaration */:
- return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer);
- case 150 /* PropertySignature */:
- return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
- case 151 /* PropertyDeclaration */:
- return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
- default:
- return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind);
- }
- }
- function transformJSDocType(node) {
- if (node === undefined) {
- return undefined;
- }
- switch (node.kind) {
- case 275 /* JSDocAllType */:
- case 276 /* JSDocUnknownType */:
- return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 279 /* JSDocOptionalType */:
- return transformJSDocOptionalType(node);
- case 278 /* JSDocNonNullableType */:
- return transformJSDocType(node.type);
- case 277 /* JSDocNullableType */:
- return transformJSDocNullableType(node);
- case 281 /* JSDocVariadicType */:
- return transformJSDocVariadicType(node);
- case 280 /* JSDocFunctionType */:
- return transformJSDocFunctionType(node);
- case 148 /* Parameter */:
- return transformJSDocParameter(node);
- case 161 /* TypeReference */:
- return transformJSDocTypeReference(node);
- default:
- var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined);
- ts.setEmitFlags(visited, 1 /* SingleLine */);
- return visited;
- }
- }
- function transformJSDocOptionalType(node) {
- return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
- }
- function transformJSDocNullableType(node) {
- return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
- }
- function transformJSDocVariadicType(node) {
- return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
- }
- function transformJSDocFunctionType(node) {
- var parameters = node.parameters && node.parameters.map(transformJSDocType);
- return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type);
- }
- function transformJSDocParameter(node) {
- var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 281 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
- var name = node.name || (isRest ? "rest" : "arg" + index);
- var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
- return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
- }
- function transformJSDocTypeReference(node) {
- var name = node.typeName;
- var args = node.typeArguments;
- if (ts.isIdentifier(node.typeName)) {
- if (ts.isJSDocIndexSignature(node)) {
- return transformJSDocIndexSignature(node);
- }
- var text = node.typeName.text;
- switch (node.typeName.text) {
- case "String":
- case "Boolean":
- case "Object":
- case "Number":
- text = text.toLowerCase();
- break;
- case "array":
- case "date":
- case "promise":
- text = text[0].toUpperCase() + text.slice(1);
- break;
- }
- name = ts.createIdentifier(text);
- if ((text === "Array" || text === "Promise") && !node.typeArguments) {
- args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
- }
- else {
- args = ts.visitNodes(node.typeArguments, transformJSDocType);
- }
- }
- return ts.createTypeReferenceNode(name, args);
- }
- function transformJSDocIndexSignature(node) {
- var index = ts.createParameter(
- /*decorators*/ undefined,
- /*modifiers*/ undefined,
- /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s",
- /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []),
- /*initializer*/ undefined);
- var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
- ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
- return indexSignature;
- }
- })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var convertFunctionToES6Class;
- (function (convertFunctionToES6Class) {
- var refactorName = "Convert to ES2015 class";
- var actionName = "convert";
- var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (!ts.isInJavaScriptFile(context.file)) {
- return undefined;
- }
- var symbol = getConstructorSymbol(context);
- if (!symbol) {
- return undefined;
- }
- if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) {
- symbol = symbol.valueDeclaration.initializer.symbol;
- }
- if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) {
- return [
- {
- name: refactorName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName
- }
- ]
- }
- ];
- }
- }
- function getEditsForAction(context, action) {
- // Somehow wrong action got invoked?
- if (actionName !== action) {
- return undefined;
- }
- var sourceFile = context.file;
- var ctorSymbol = getConstructorSymbol(context);
- var deletedNodes = [];
- var deletes = [];
- if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
- return undefined;
- }
- var ctorDeclaration = ctorSymbol.valueDeclaration;
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var precedingNode;
- var newClassDeclaration;
- switch (ctorDeclaration.kind) {
- case 232 /* FunctionDeclaration */:
- precedingNode = ctorDeclaration;
- deleteNode(ctorDeclaration);
- newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
- break;
- case 230 /* VariableDeclaration */:
- precedingNode = ctorDeclaration.parent.parent;
- if (ctorDeclaration.parent.declarations.length === 1) {
- deleteNode(precedingNode);
- }
- else {
- deleteNode(ctorDeclaration, /*inList*/ true);
- }
- newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
- break;
- }
- if (!newClassDeclaration) {
- return undefined;
- }
- // Because the preceding node could be touched, we need to insert nodes before delete nodes.
- changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
- for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) {
- var deleteCallback = deletes_1[_i];
- deleteCallback();
- }
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined,
- };
- function deleteNode(node, inList) {
- if (inList === void 0) { inList = false; }
- if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) {
- // Parent node has already been deleted; do nothing
- return;
- }
- deletedNodes.push(node);
- if (inList) {
- deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); });
- }
- else {
- deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); });
- }
- }
- function createClassElementsFromSymbol(symbol) {
- var memberElements = [];
- // all instance members are stored in the "member" array of symbol
- if (symbol.members) {
- symbol.members.forEach(function (member) {
- var memberElement = createClassElement(member, /*modifiers*/ undefined);
- if (memberElement) {
- memberElements.push(memberElement);
- }
- });
- }
- // all static members are stored in the "exports" array of symbol
- if (symbol.exports) {
- symbol.exports.forEach(function (member) {
- var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]);
- if (memberElement) {
- memberElements.push(memberElement);
- }
- });
- }
- return memberElements;
- function shouldConvertDeclaration(_target, source) {
- // Right now the only thing we can convert are function expressions - other values shouldn't get
- // transformed. We can update this once ES public class properties are available.
- return ts.isFunctionLike(source);
- }
- function createClassElement(symbol, modifiers) {
- // both properties and methods are bound as property symbols
- if (!(symbol.flags & 4 /* Property */)) {
- return;
- }
- var memberDeclaration = symbol.valueDeclaration;
- var assignmentBinaryExpression = memberDeclaration.parent;
- if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
- return;
- }
- // 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 === 214 /* ExpressionStatement */
- ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
- deleteNode(nodeToDelete);
- if (!assignmentBinaryExpression.right) {
- return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
- /*type*/ undefined, /*initializer*/ undefined);
- }
- switch (assignmentBinaryExpression.right.kind) {
- case 190 /* FunctionExpression */: {
- var functionExpression = assignmentBinaryExpression.right;
- var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */));
- var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
- /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- copyComments(assignmentBinaryExpression, method);
- return method;
- }
- case 191 /* ArrowFunction */: {
- var arrowFunction = assignmentBinaryExpression.right;
- var arrowFunctionBody = arrowFunction.body;
- var bodyBlock = void 0;
- // case 1: () => { return [1,2,3] }
- if (arrowFunctionBody.kind === 211 /* Block */) {
- bodyBlock = arrowFunctionBody;
- }
- else {
- bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
- }
- var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */));
- var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
- /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- copyComments(assignmentBinaryExpression, method);
- return method;
- }
- default: {
- // Don't try to declare members in JavaScript files
- if (ts.isSourceFileJavaScript(sourceFile)) {
- return;
- }
- var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
- /*type*/ undefined, assignmentBinaryExpression.right);
- copyComments(assignmentBinaryExpression.parent, prop);
- return prop;
- }
- }
- }
- }
- function copyComments(sourceNode, targetNode) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
- if (kind === 3 /* MultiLineCommentTrivia */) {
- // Remove leading /*
- pos += 2;
- // Remove trailing */
- end -= 2;
- }
- else {
- // Remove leading //
- pos += 2;
- }
- ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl);
- });
- }
- function createClassFromVariableDeclaration(node) {
- var initializer = node.initializer;
- if (!initializer || initializer.kind !== 190 /* FunctionExpression */) {
- return undefined;
- }
- if (node.name.kind !== 71 /* Identifier */) {
- return undefined;
- }
- var memberElements = createClassElementsFromSymbol(initializer.symbol);
- if (initializer.body) {
- memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
- }
- var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */);
- var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
- /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
- // Don't call copyComments here because we'll already leave them in place
- return cls;
- }
- function createClassFromFunctionDeclaration(node) {
- var memberElements = createClassElementsFromSymbol(ctorSymbol);
- if (node.body) {
- memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
- }
- var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */);
- var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
- /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
- // Don't call copyComments here because we'll already leave them in place
- return cls;
- }
- function getModifierKindFromSource(source, kind) {
- return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
- }
- }
- function getConstructorSymbol(_a) {
- var startPosition = _a.startPosition, file = _a.file, program = _a.program;
- var checker = program.getTypeChecker();
- var token = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- return checker.getSymbolAtLocation(token);
- }
- })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var actionName = "Convert to ES6 module";
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module);
- refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- var file = context.file, startPosition = context.startPosition;
- if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) {
- return undefined;
- }
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- return !isAtTriggerLocation(file, node) ? undefined : [
- {
- name: actionName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function isAtTriggerLocation(sourceFile, node, onSecondTry) {
- if (onSecondTry === void 0) { onSecondTry = false; }
- switch (node.kind) {
- case 185 /* CallExpression */:
- return isAtTopLevelRequire(node);
- case 183 /* PropertyAccessExpression */:
- return ts.isExportsOrModuleExportsOrAlias(sourceFile, node)
- || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression);
- case 231 /* VariableDeclarationList */:
- return isVariableDeclarationTriggerLocation(ts.firstOrUndefined(node.declarations));
- case 230 /* VariableDeclaration */:
- return isVariableDeclarationTriggerLocation(node);
- default:
- return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node)
- || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true);
- }
- function isVariableDeclarationTriggerLocation(decl) {
- return !!decl && !!decl.initializer && ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer);
- }
- }
- function isAtTopLevelRequire(call) {
- if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) {
- return false;
- }
- var propAccess = call.parent;
- var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess;
- if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) {
- return true;
- }
- if (!ts.isVariableDeclaration(varDecl)) {
- return false;
- }
- var varDeclList = varDecl.parent;
- if (varDeclList.kind !== 231 /* VariableDeclarationList */) {
- return false;
- }
- var varStatement = varDeclList.parent;
- return varStatement.kind === 212 /* VariableStatement */ && varStatement.parent.kind === 272 /* SourceFile */;
- }
- function getEditsForAction(context, _actionName) {
- ts.Debug.assertEqual(actionName, _actionName);
- var file = context.file, program = context.program;
- ts.Debug.assert(ts.isSourceFileJavaScript(file));
- var edits = ts.textChanges.ChangeTracker.with(context, function (changes) {
- var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target);
- if (moduleExportsChangedToDefault) {
- for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
- var importingFile = _a[_i];
- fixImportOfModuleExports(importingFile, file, changes);
- }
- }
- });
- return { edits: edits, renameFilename: undefined, renameLocation: undefined };
- }
- function fixImportOfModuleExports(importingFile, exportingFile, changes) {
- for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
- var moduleSpecifier = _a[_i];
- var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
- if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
- continue;
- }
- var parent = moduleSpecifier.parent;
- switch (parent.kind) {
- case 252 /* ExternalModuleReference */: {
- var importEq = parent.parent;
- changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text));
- break;
- }
- case 185 /* CallExpression */: {
- var call = parent;
- if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) {
- changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default"));
- }
- break;
- }
- }
- }
- }
- /** @returns Whether we converted a `module.exports =` to a default export. */
- function convertFileToEs6Module(sourceFile, checker, changes, target) {
- var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
- var exports = collectExportRenames(sourceFile, checker, identifiers);
- convertExportsAccesses(sourceFile, exports, changes);
- var moduleExportsChangedToDefault = false;
- for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
- var statement = _a[_i];
- var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports);
- moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
- }
- return moduleExportsChangedToDefault;
- }
- function collectExportRenames(sourceFile, checker, identifiers) {
- var res = ts.createMap();
- forEachExportReference(sourceFile, function (node) {
- var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
- if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
- || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) {
- // Unconditionally add an underscore in case `text` is a keyword.
- res.set(text, makeUniqueName("_" + text, identifiers));
- }
- });
- return res;
- }
- function convertExportsAccesses(sourceFile, exports, changes) {
- forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
- if (isAssignmentLhs) {
- return;
- }
- var text = node.name.text;
- changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
- });
- }
- function forEachExportReference(sourceFile, cb) {
- sourceFile.forEachChild(function recur(node) {
- if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
- var parent = node.parent;
- cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */);
- }
- node.forEachChild(recur);
- });
- }
- function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) {
- switch (statement.kind) {
- case 212 /* VariableStatement */:
- convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target);
- return false;
- case 214 /* ExpressionStatement */: {
- var expression = statement.expression;
- switch (expression.kind) {
- case 185 /* CallExpression */: {
- if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) {
- // For side-effecting require() call, just make a side-effecting import.
- changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text));
- }
- return false;
- }
- case 198 /* BinaryExpression */: {
- var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
- return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports);
- }
- }
- }
- // falls through
- default:
- return false;
- }
- }
- function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) {
- var declarationList = statement.declarationList;
- var foundImport = false;
- var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
- var name = decl.name, initializer = decl.initializer;
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
- // `const alias = module.exports;` can be removed.
- foundImport = true;
- return [];
- }
- if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) {
- foundImport = true;
- return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target);
- }
- else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) {
- foundImport = true;
- return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers);
- }
- else {
- // Move it out to its own variable statement.
- return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
- }
- });
- if (foundImport) {
- // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- }
- }
- /** Converts `const name = require("moduleSpecifier").propertyName` */
- function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) {
- switch (name.kind) {
- case 178 /* ObjectBindingPattern */:
- case 179 /* ArrayBindingPattern */: {
- // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
- var tmp = makeUniqueName(propertyName, identifiers);
- return [
- makeSingleImport(tmp, propertyName, moduleSpecifier),
- makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
- ];
- }
- case 71 /* Identifier */:
- // `const a = require("b").c` --> `import { c as a } from "./b";
- return [makeSingleImport(name.text, propertyName, moduleSpecifier)];
- default:
- ts.Debug.assertNever(name);
- }
- }
- function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) {
- if (!ts.isPropertyAccessExpression(left)) {
- return false;
- }
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
- // `const alias = module.exports;` or `module.exports = alias;` can be removed.
- changes.deleteNode(sourceFile, statement);
- }
- else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
- }
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- return changedToDefaultExport;
- }
- }
- else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
- convertNamedExport(sourceFile, statement, left.name, right, changes, exports);
- }
- return false;
- var _a;
- }
- /**
- * Convert `module.exports = { ... }` to individual exports..
- * We can't always do this if the module has interesting members -- then it will be a default export instead.
- */
- function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
- switch (prop.kind) {
- case 155 /* GetAccessor */:
- case 156 /* SetAccessor */:
- // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
- case 269 /* ShorthandPropertyAssignment */:
- case 270 /* SpreadAssignment */:
- return undefined;
- case 268 /* PropertyAssignment */:
- return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer);
- case 153 /* MethodDeclaration */:
- return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop);
- default:
- ts.Debug.assertNever(prop);
- }
- });
- }
- function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) {
- // If "originalKeywordKind" was set, this is e.g. `exports.
- var text = propertyName.text;
- var rename = exports.get(text);
- if (rename !== undefined) {
- /*
- const _class = 0;
- export { _class as class };
- */
- var newNodes = [
- makeConst(/*modifiers*/ undefined, rename, right),
- makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
- ];
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- }
- else {
- changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true });
- }
- }
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
- switch (exported.kind) {
- case 190 /* FunctionExpression */:
- case 191 /* ArrowFunction */: {
- // `module.exports = function f() {}` --> `export default function f() {}`
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 203 /* ClassExpression */: {
- // `module.exports = class C {}` --> `export default class C {}`
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 185 /* CallExpression */:
- if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) {
- return convertReExportAll(exported.arguments[0], checker);
- }
- // falls through
- default:
- // `module.exports = 0;` --> `export default 0;`
- return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
- }
- }
- function convertReExportAll(reExported, checker) {
- // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
- var moduleSpecifier = reExported.text;
- var moduleSymbol = checker.getSymbolAtLocation(reExported);
- var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
- return exports.has("export=")
- ? [[reExportDefault(moduleSpecifier)], true]
- : !exports.has("default")
- ? [[reExportStar(moduleSpecifier)], false]
- // If there's some non-default export, must include both `export *` and `export default`.
- : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
- }
- function reExportStar(moduleSpecifier) {
- return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
- }
- function reExportDefault(moduleSpecifier) {
- return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
- }
- function convertExportsDotXEquals(name, exported) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */)];
- switch (exported.kind) {
- case 190 /* FunctionExpression */: {
- var expressionName = exported.name;
- if (expressionName && expressionName.text !== name) {
- // `exports.f = function g() {}` -> `export const f = function g() {}`
- return exportConst();
- }
- }
- // falls through
- case 191 /* ArrowFunction */:
- // `exports.f = function() {}` --> `export function f() {}`
- return functionExpressionToDeclaration(name, modifiers, exported);
- case 203 /* ClassExpression */:
- // `exports.C = class {}` --> `export class C {}`
- return classExpressionToDeclaration(name, modifiers, exported);
- default:
- return exportConst();
- }
- function exportConst() {
- // `exports.x = 0;` --> `export const x = 0;`
- return makeConst(modifiers, ts.createIdentifier(name), exported);
- }
- }
- /**
- * Converts `const <> = require("x");`.
- * Returns nodes that will replace the variable declaration for the commonjs import.
- * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
- */
- function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) {
- switch (name.kind) {
- case 178 /* 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
- : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
- });
- if (importSpecifiers) {
- return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
- }
- }
- // falls through -- object destructuring has an interesting pattern and must be a variable declaration
- case 179 /* ArrayBindingPattern */: {
- /*
- import x from "x";
- const [a, b, c] = x;
- */
- var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers);
- return [
- makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
- makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
- ];
- }
- case 71 /* Identifier */:
- return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers);
- default:
- ts.Debug.assertNever(name);
- }
- }
- /**
- * Convert `import x = require("x").`
- * Also converts uses like `x.y()` to `y()` and uses a named import.
- */
- function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) {
- var nameSymbol = checker.getSymbolAtLocation(name);
- // Maps from module property name to name actually used. (The same if there isn't shadowing.)
- var namedBindingsNames = ts.createMap();
- // True if there is some non-property use like `x()` or `f(x)`.
- var needDefaultImport = false;
- for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
- var use = _a[_i];
- if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
- // This was a use of a different symbol with the same name, due to shadowing. Ignore.
- continue;
- }
- var parent = use.parent;
- if (ts.isPropertyAccessExpression(parent)) {
- var expression = parent.expression, propertyName = parent.name.text;
- ts.Debug.assert(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);
- }
- changes.replaceNode(file, parent, ts.createIdentifier(idName));
- }
- else {
- needDefaultImport = true;
- }
- }
- var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
- var propertyName = _a[0], idName = _a[1];
- return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
- }));
- if (!namedBindings) {
- // If it was unused, ensure that we at least import *something*.
- needDefaultImport = true;
- }
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
- }
- // Identifiers helpers
- function makeUniqueName(name, identifiers) {
- while (identifiers.original.has(name) || identifiers.additional.has(name)) {
- name = "_" + name;
- }
- identifiers.additional.set(name, true);
- return name;
- }
- function collectFreeIdentifiers(file) {
- var map = ts.createMultiMap();
- file.forEachChild(function recur(node) {
- if (ts.isIdentifier(node) && isFreeIdentifier(node)) {
- map.add(node.text, node);
- }
- node.forEachChild(recur);
- });
- return map;
- }
- function isFreeIdentifier(node) {
- var parent = node.parent;
- switch (parent.kind) {
- case 183 /* PropertyAccessExpression */:
- return parent.name !== node;
- case 180 /* BindingElement */:
- return parent.propertyName !== node;
- default:
- return true;
- }
- }
- // Node helpers
- function functionExpressionToDeclaration(name, additionalModifiers, fn) {
- return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
- ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
- }
- function classExpressionToDeclaration(name, additionalModifiers, cls) {
- return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
- ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
- }
- function makeSingleImport(localName, propertyName, moduleSpecifier) {
- return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
- : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
- }
- function makeImport(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier));
- }
- function makeImportSpecifier(propertyName, name) {
- return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
- }
- function makeConst(modifiers, name, init) {
- return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
- }
- function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
- return ts.createExportDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
- }
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
+///
+///
///
///
/* @internal */
@@ -99478,7 +99920,7 @@ var ts;
}
else if (ts.isVariableStatement(node)) {
var numInitializers = 0;
- var lastInitializer = undefined;
+ var lastInitializer = void 0;
for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (declaration.initializer) {
@@ -99595,7 +100037,7 @@ var ts;
switch (node.kind) {
case 232 /* FunctionDeclaration */:
case 233 /* ClassDeclaration */:
- if (node.parent.kind === 272 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) {
+ if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
// You cannot extract global declarations
(errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
}
@@ -99875,12 +100317,12 @@ var ts;
var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text);
var isJS = ts.isInJavaScriptFile(scope);
var functionName = ts.createIdentifier(functionNameText);
- var returnType = undefined;
+ var returnType;
var parameters = [];
var callArguments = [];
var writes;
usagesInScope.forEach(function (usage, name) {
- var typeNode = undefined;
+ var typeNode;
if (!isJS) {
var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
// Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
@@ -100167,7 +100609,7 @@ var ts;
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function getContainingVariableDeclarationIfInList(node, scope) {
- var prevNode = undefined;
+ var prevNode;
while (node !== undefined && node !== scope) {
if (ts.isVariableDeclaration(node) &&
node.initializer === prevNode &&
@@ -100192,16 +100634,16 @@ var ts;
ts.Debug.assert(fileName === renameFilename);
for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) {
var change = textChanges_3[_b];
- var span_15 = change.span, newText = change.newText;
+ var span_14 = change.span, newText = change.newText;
var index = newText.indexOf(functionNameText);
if (index !== -1) {
- lastPos = span_15.start + delta + index;
+ lastPos = span_14.start + delta + index;
// If the reference comes first, return immediately.
if (!isDeclaredBeforeUse) {
return lastPos;
}
}
- delta += newText.length - span_15.length;
+ delta += newText.length - span_14.length;
}
}
// If the declaration comes first, return the position of the last occurrence.
@@ -100210,7 +100652,7 @@ var ts;
return lastPos;
}
function getFirstDeclaration(type) {
- var firstDeclaration = undefined;
+ var firstDeclaration;
var symbol = type.symbol;
if (symbol && symbol.declarations) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
@@ -100332,7 +100774,7 @@ var ts;
function getNodeToInsertPropertyBefore(maxPos, scope) {
var members = scope.members;
ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one.
- var prevMember = undefined;
+ var prevMember;
var allProperties = true;
for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
var member = members_6[_i];
@@ -100354,7 +100796,7 @@ var ts;
}
function getNodeToInsertConstantBefore(node, scope) {
ts.Debug.assert(!ts.isClassLike(scope));
- var prevScope = undefined;
+ var prevScope;
for (var curr = node; curr !== scope; curr = curr.parent) {
if (isScope(curr)) {
prevScope = curr;
@@ -100362,7 +100804,7 @@ var ts;
}
for (var curr = (prevScope || node).parent;; curr = curr.parent) {
if (isBlockLike(curr)) {
- var prevStatement = undefined;
+ var prevStatement = void 0;
for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) {
var statement = _a[_i];
if (statement.pos > node.pos) {
@@ -100427,13 +100869,13 @@ var ts;
var visibleDeclarationsInExtractedRange = [];
var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID
var exposedVariableDeclarations = [];
- var firstExposedNonVariableDeclaration = undefined;
+ var firstExposedNonVariableDeclaration;
var expression = !isReadonlyArray(targetRange.range)
? targetRange.range
: targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0])
? targetRange.range[0].expression
: undefined;
- var expressionDiagnostic = undefined;
+ var expressionDiagnostic;
if (expression === undefined) {
var statements = targetRange.range;
var start = ts.first(statements).getStart();
@@ -100511,7 +100953,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_10 = function (i) {
+ var _loop_11 = 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
@@ -100521,7 +100963,7 @@ var ts;
constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
}
var hasWrite = false;
- var readonlyClassPropertyWrite = undefined;
+ var readonlyClassPropertyWrite;
usagesPerScope[i].usages.forEach(function (value) {
if (value.usage === 2 /* Write */) {
hasWrite = true;
@@ -100551,7 +100993,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_10(i);
+ _loop_11(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function hasTypeParameters(node) {
@@ -100819,165 +101261,7 @@ var ts;
})(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var installTypesForPackage;
- (function (installTypesForPackage) {
- var refactorName = "Install missing types package";
- var actionName = "install";
- var description = "Install missing types package";
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) {
- // Then it will be available via `fixCannotFindModule`.
- return undefined;
- }
- var action = getAction(context);
- return action && [
- {
- name: refactorName,
- description: description,
- actions: [
- {
- description: action.description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function getEditsForAction(context, _actionName) {
- ts.Debug.assertEqual(actionName, _actionName);
- var action = getAction(context); // Should be defined if we said there was an action available.
- return {
- edits: [],
- renameFilename: undefined,
- renameLocation: undefined,
- commands: action.commands,
- };
- }
- function getAction(context) {
- var file = context.file, startPosition = context.startPosition;
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- if (!ts.isStringLiteral(node) || !isModuleIdentifier(node)) {
- return undefined;
- }
- var resolvedTo = ts.getResolvedModule(file, node.text);
- // Still offer to install types if it resolved to e.g. a ".js" file.
- // `tryGetCodeActionForInstallPackageTypes` will verify that we're looking for a valid package name,
- // so the fix won't trigger for imports of ".js" files that couldn't be better replaced by typings.
- if (resolvedTo && ts.extensionIsTypeScript(resolvedTo.extension)) {
- return undefined;
- }
- return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, file.fileName, node.text);
- }
- function isModuleIdentifier(node) {
- switch (node.parent.kind) {
- case 242 /* ImportDeclaration */:
- case 252 /* ExternalModuleReference */:
- return true;
- default:
- return false;
- }
- }
- })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var installTypesForPackage;
- (function (installTypesForPackage) {
- var actionName = "Convert to default import";
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import);
- refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- var file = context.file, startPosition = context.startPosition, program = context.program;
- if (!ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
- return undefined;
- }
- var importInfo = getConvertibleImportAtPosition(file, startPosition);
- if (!importInfo) {
- return undefined;
- }
- var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
- if (!(resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) {
- return undefined;
- }
- return [
- {
- name: actionName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function getEditsForAction(context, _actionName) {
- var file = context.file, startPosition = context.startPosition;
- ts.Debug.assertEqual(actionName, _actionName);
- var importInfo = getConvertibleImportAtPosition(file, startPosition);
- if (!importInfo) {
- return undefined;
- }
- var importStatement = importInfo.importStatement, name = importInfo.name, moduleSpecifier = importInfo.moduleSpecifier;
- var newImportClause = ts.createImportClause(name, /*namedBindings*/ undefined);
- var newImportStatement = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newImportClause, moduleSpecifier);
- return {
- edits: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, importStatement, newImportStatement); }),
- renameFilename: undefined,
- renameLocation: undefined,
- };
- }
- function getConvertibleImportAtPosition(file, startPosition) {
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- while (true) {
- switch (node.kind) {
- case 241 /* ImportEqualsDeclaration */:
- var eq = node;
- var moduleReference = eq.moduleReference;
- return moduleReference.kind === 252 /* ExternalModuleReference */ && ts.isStringLiteral(moduleReference.expression)
- ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression }
- : undefined;
- case 242 /* ImportDeclaration */:
- var d = node;
- var importClause = d.importClause;
- return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(d.moduleSpecifier)
- ? { importStatement: d, name: importClause.namedBindings.name, moduleSpecifier: d.moduleSpecifier }
- : undefined;
- // For known child node kinds of convertible imports, try again with parent node.
- case 244 /* NamespaceImport */:
- case 252 /* ExternalModuleReference */:
- case 91 /* ImportKeyword */:
- case 71 /* Identifier */:
- case 9 /* StringLiteral */:
- case 39 /* AsteriskToken */:
- break;
- default:
- return undefined;
- }
- node = node.parent;
- }
- }
- })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-///
-///
-///
///
-///
-///
///
///
///
@@ -100999,6 +101283,7 @@ var ts;
///
///
///
+///
///
///
///
@@ -101530,20 +101815,8 @@ var ts;
}
function getDeclarationName(declaration) {
var name = ts.getNameOfDeclaration(declaration);
- if (name) {
- var result_6 = ts.getTextOfIdentifierOrLiteral(name);
- if (result_6 !== undefined) {
- return result_6;
- }
- if (name.kind === 146 /* ComputedPropertyName */) {
- var expr = name.expression;
- if (expr.kind === 183 /* PropertyAccessExpression */) {
- return expr.name.text;
- }
- return ts.getTextOfIdentifierOrLiteral(expr);
- }
- }
- return undefined;
+ return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) :
+ name.kind === 146 /* ComputedPropertyName */ && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined);
}
function visit(node) {
switch (node.kind) {
@@ -102130,6 +102403,10 @@ var ts;
var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
return semanticDiagnostics.concat(declarationDiagnostics);
}
+ function getSuggestionDiagnostics(fileName) {
+ synchronizeHostData();
+ return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program);
+ }
function getCompilerOptionsDiagnostics() {
synchronizeHostData();
return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken));
@@ -102152,9 +102429,7 @@ var ts;
var sourceFile = getValidSourceFile(fileName);
var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (node === sourceFile) {
- return undefined;
- }
- if (ts.isLabelName(node)) {
+ // Avoid giving quickInfo for the sourceFile as a whole.
return undefined;
}
var typeChecker = program.getTypeChecker();
@@ -102163,6 +102438,11 @@ var ts;
// Try getting just type at this position and show
switch (node.kind) {
case 71 /* Identifier */:
+ if (ts.isLabelName(node)) {
+ // Type here will be 'any', avoid displaying this.
+ return undefined;
+ }
+ // falls through
case 183 /* PropertyAccessExpression */:
case 145 /* QualifiedName */:
case 99 /* ThisKeyword */:
@@ -102170,27 +102450,25 @@ var ts;
case 97 /* SuperKeyword */:
// For the identifiers/this/super etc get the type at position
var type = typeChecker.getTypeAtLocation(node);
- if (type) {
- return {
- kind: "" /* unknown */,
- kindModifiers: "" /* none */,
- textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
- displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)),
- documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type.symbol ? type.symbol.getJsDocTags() : undefined
- };
- }
+ return type && {
+ kind: "" /* unknown */,
+ kindModifiers: "" /* none */,
+ textSpan: ts.createTextSpanFromNode(node, sourceFile),
+ displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)),
+ documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined,
+ tags: type.symbol ? type.symbol.getJsDocTags() : undefined
+ };
}
return undefined;
}
- var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node);
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags;
return {
- kind: displayPartsDocumentationsAndKind.symbolKind,
+ kind: symbolKind,
kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
- textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
- displayParts: displayPartsDocumentationsAndKind.displayParts,
- documentation: displayPartsDocumentationsAndKind.documentation,
- tags: displayPartsDocumentationsAndKind.tags
+ textSpan: ts.createTextSpanFromNode(node, sourceFile),
+ displayParts: displayParts,
+ documentation: documentation,
+ tags: tags,
};
}
function getSymbolAtLocationForQuickInfo(node, checker) {
@@ -102198,11 +102476,9 @@ var ts;
&& ts.isPropertyAssignment(node.parent)
&& node.parent.name === node) {
var type = checker.getContextualType(node.parent.parent);
- if (type) {
- var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node));
- if (property) {
- return property;
- }
+ var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node));
+ if (property) {
+ return property;
}
}
return checker.getSymbolAtLocation(node);
@@ -102465,7 +102741,7 @@ var ts;
ts.Debug.assert(scope.type === "file");
var sourceFile = getValidSourceFile(scope.fileName);
var formatContext = ts.formatting.getFormatContext(formatOptions);
- return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host);
+ return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program);
}
function applyCodeActionCommand(fileName, actionOrUndefined) {
var action = typeof fileName === "string" ? actionOrUndefined : fileName;
@@ -102479,6 +102755,7 @@ var ts;
: Promise.reject("Host does not implement `installPackage`");
default:
ts.Debug.fail();
+ // TODO: Debug.assertNever(action); will only work if there is more than one type.
}
}
function getDocCommentTemplateAtPosition(fileName, position) {
@@ -102562,7 +102839,7 @@ var ts;
if (!ts.isInComment(sourceFile, matchPosition)) {
continue;
}
- var descriptor = undefined;
+ var descriptor = void 0;
for (var i = 0; i < descriptors.length; i++) {
if (matchArray[i + firstDescriptorCaptureIndex]) {
descriptor = descriptors[i];
@@ -102673,6 +102950,7 @@ var ts;
cleanupSemanticCache: cleanupSemanticCache,
getSyntacticDiagnostics: getSyntacticDiagnostics,
getSemanticDiagnostics: getSemanticDiagnostics,
+ getSuggestionDiagnostics: getSuggestionDiagnostics,
getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics,
getSyntacticClassifications: getSyntacticClassifications,
getSemanticClassifications: getSemanticClassifications,
@@ -102790,20 +103068,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_7 = [];
+ var result_6 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072 /* Union */) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_7.push(symbol);
+ result_6.push(symbol);
}
});
- return result_7;
+ return result_6;
}
if (symbol) {
- result_7.push(symbol);
- return result_7;
+ result_6.push(symbol);
+ return result_6;
}
}
return undefined;
@@ -103050,24 +103328,23 @@ var ts;
return textSpan(node);
}
if (node.kind === 198 /* BinaryExpression */) {
- var binaryExpression = node;
+ 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
// [a, b, c] = expression or
// {a, b, c} = expression
- if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) {
- return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left);
+ if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
+ return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left);
}
- if (binaryExpression.operatorToken.kind === 58 /* EqualsToken */ &&
- ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) {
+ if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
// Set breakpoint on assignment expression element of destructuring pattern
// a = expression of
// [a = expression, b, c] = someExpression or
// { a = expression, b, c } = someExpression
return textSpan(node);
}
- if (binaryExpression.operatorToken.kind === 26 /* CommaToken */) {
- return spanInNode(binaryExpression.left);
+ if (operatorToken.kind === 26 /* CommaToken */) {
+ return spanInNode(left);
}
}
if (ts.isExpressionNode(node)) {
@@ -103095,46 +103372,49 @@ var ts;
break;
}
}
- // If this is name of property assignment, set breakpoint in the initializer
- if (node.parent.kind === 268 /* PropertyAssignment */ &&
- node.parent.name === node &&
- !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
- return spanInNode(node.parent.initializer);
- }
- // Breakpoint in type assertion goes to its operand
- if (node.parent.kind === 188 /* TypeAssertionExpression */ && node.parent.type === node) {
- return spanInNextNode(node.parent.type);
- }
- // return type of function go to previous token
- if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
- return spanInPreviousNode(node);
- }
- // initializer of variable/parameter declaration go to previous node
- if ((node.parent.kind === 230 /* VariableDeclaration */ ||
- node.parent.kind === 148 /* Parameter */)) {
- var paramOrVarDecl = node.parent;
- if (paramOrVarDecl.initializer === node ||
- paramOrVarDecl.type === node ||
- ts.isAssignmentOperator(node.kind)) {
- return spanInPreviousNode(node);
+ switch (node.parent.kind) {
+ case 268 /* 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 188 /* TypeAssertionExpression */:
+ // Breakpoint in type assertion goes to its operand
+ if (node.parent.type === node) {
+ return spanInNextNode(node.parent.type);
+ }
+ break;
+ case 230 /* VariableDeclaration */:
+ case 148 /* 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)) {
+ return spanInPreviousNode(node);
+ }
+ break;
}
- }
- if (node.parent.kind === 198 /* BinaryExpression */) {
- var binaryExpression = node.parent;
- if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) &&
- (binaryExpression.right === node ||
- binaryExpression.operatorToken === node)) {
- // If initializer of destructuring assignment move to previous token
- return spanInPreviousNode(node);
+ case 198 /* BinaryExpression */: {
+ var left = node.parent.left;
+ if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
+ // If initializer of destructuring assignment move to previous token
+ return spanInPreviousNode(node);
+ }
+ break;
}
+ default:
+ // return type of function go to previous token
+ if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
+ return spanInPreviousNode(node);
+ }
}
// Default go to parent to set the breakpoint
return spanInNode(node.parent);
}
}
function textSpanFromVariableDeclaration(variableDeclaration) {
- if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ &&
- variableDeclaration.parent.declarations[0] === variableDeclaration) {
+ if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
// First declaration - include let keyword
return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
}
@@ -103159,7 +103439,7 @@ var ts;
variableDeclaration.parent.parent.kind === 220 /* ForOfStatement */) {
return textSpanFromVariableDeclaration(variableDeclaration);
}
- if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ &&
+ if (ts.isVariableDeclarationList(variableDeclaration.parent) &&
variableDeclaration.parent.declarations[0] !== variableDeclaration) {
// If we cannot set breakpoint on this declaration, set it on previous one
// Because the variable declaration may be binding pattern and
@@ -103717,8 +103997,7 @@ var ts;
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
length: diagnostic.length,
- /// TODO: no need for the tolowerCase call
- category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(diagnostic),
code: diagnostic.code
};
}
@@ -103768,7 +104047,7 @@ var ts;
};
LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) {
var newLine = ts.getNewLineOrDefaultFromHost(this.host);
- return ts.realizeDiagnostics(diagnostics, newLine);
+ return realizeDiagnostics(diagnostics, newLine);
};
LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) {
var _this = this;
@@ -103806,6 +104085,10 @@ var ts;
return _this.realizeDiagnostics(diagnostics);
});
};
+ LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) {
+ var _this = this;
+ return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); });
+ };
LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () {
var _this = this;
return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () {
diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts
index ca9bf106e1e..e4bf5eec894 100644
--- a/lib/typescriptServices.d.ts
+++ b/lib/typescriptServices.d.ts
@@ -1811,7 +1811,7 @@ declare namespace ts {
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined;
- getJsxIntrinsicTagNames(): Symbol[];
+ getJsxIntrinsicTagNamesAt(location: Node): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
@@ -2192,11 +2192,25 @@ declare namespace ts {
interface IndexType extends InstantiableType {
type: InstantiableType | UnionOrIntersectionType;
}
- interface ConditionalType extends InstantiableType {
+ interface ConditionalRoot {
+ node: ConditionalTypeNode;
checkType: Type;
extendsType: Type;
trueType: Type;
falseType: Type;
+ isDistributive: boolean;
+ inferTypeParameters: TypeParameter[];
+ outerTypeParameters?: TypeParameter[];
+ instantiations?: Map;
+ aliasSymbol: Symbol;
+ aliasTypeArguments: Type[];
+ }
+ interface ConditionalType extends InstantiableType {
+ root: ConditionalRoot;
+ checkType: Type;
+ extendsType: Type;
+ resolvedTrueType?: Type;
+ resolvedFalseType?: Type;
}
interface SubstitutionType extends InstantiableType {
typeParameter: TypeParameter;
@@ -2222,41 +2236,13 @@ declare namespace ts {
}
enum InferencePriority {
NakedTypeVariable = 1,
- MappedType = 2,
- ReturnType = 4,
- NoConstraints = 8,
- AlwaysStrict = 16,
+ HomomorphicMappedType = 2,
+ MappedTypeConstraint = 4,
+ ReturnType = 8,
+ NoConstraints = 16,
+ AlwaysStrict = 32,
+ PriorityImpliesUnion = 12,
}
- interface InferenceInfo {
- typeParameter: TypeParameter;
- candidates: Type[];
- contraCandidates: Type[];
- inferredType: Type;
- priority: InferencePriority;
- topLevel: boolean;
- isFixed: boolean;
- }
- enum InferenceFlags {
- None = 0,
- InferUnionTypes = 1,
- NoDefault = 2,
- AnyDefault = 4,
- }
- /**
- * Ternary values are defined such that
- * x & y is False if either x or y is False.
- * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
- * x & y is True if both x and y are True.
- * x | y is False if both x and y are False.
- * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
- * x | y is True if either x or y is True.
- */
- enum Ternary {
- False = 0,
- Maybe = 1,
- True = -1,
- }
- type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary;
interface JsFileExtensionInfo {
extension: string;
isMixedContent: boolean;
@@ -2292,7 +2278,8 @@ declare namespace ts {
enum DiagnosticCategory {
Warning = 0,
Error = 1,
- Message = 2,
+ Suggestion = 2,
+ Message = 3,
}
enum ModuleResolutionKind {
Classic = 1,
@@ -3301,7 +3288,8 @@ declare namespace ts {
function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression;
function isTemplateLiteral(node: Node): node is TemplateLiteral;
function isAssertionExpression(node: Node): node is AssertionExpression;
- function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement;
+ function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement;
+ function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement;
function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement;
function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause;
/** True if node is of a kind that may contain comment text. */
@@ -4336,6 +4324,7 @@ declare namespace ts {
cleanupSemanticCache(): void;
getSyntacticDiagnostics(fileName: string): Diagnostic[];
getSemanticDiagnostics(fileName: string): Diagnostic[];
+ getSuggestionDiagnostics(fileName: string): Diagnostic[];
getCompilerOptionsDiagnostics(): Diagnostic[];
/**
* @deprecated Use getEncodedSyntacticClassifications instead.
@@ -4746,7 +4735,7 @@ declare namespace ts {
argumentCount: number;
}
interface CompletionInfo {
- /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isGlobalCompletionScope`. */
+ /** Not true for all glboal completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */
isGlobalCompletion: boolean;
isMemberCompletion: boolean;
/**
diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js
index 71de0f4e0b6..277567d22fe 100644
--- a/lib/typescriptServices.js
+++ b/lib/typescriptServices.js
@@ -949,11 +949,14 @@ var ts;
var InferencePriority;
(function (InferencePriority) {
InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
- InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType";
- InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType";
- InferencePriority[InferencePriority["NoConstraints"] = 8] = "NoConstraints";
- InferencePriority[InferencePriority["AlwaysStrict"] = 16] = "AlwaysStrict";
+ InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
+ InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint";
+ InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType";
+ InferencePriority[InferencePriority["NoConstraints"] = 16] = "NoConstraints";
+ InferencePriority[InferencePriority["AlwaysStrict"] = 32] = "AlwaysStrict";
+ InferencePriority[InferencePriority["PriorityImpliesUnion"] = 12] = "PriorityImpliesUnion";
})(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
+ /* @internal */
var InferenceFlags;
(function (InferenceFlags) {
InferenceFlags[InferenceFlags["None"] = 0] = "None";
@@ -970,6 +973,7 @@ var ts;
* x | y is Maybe if either x or y is Maybe, but neither x or y is True.
* x | y is True if either x or y is True.
*/
+ /* @internal */
var Ternary;
(function (Ternary) {
Ternary[Ternary["False"] = 0] = "False";
@@ -995,8 +999,16 @@ var ts;
(function (DiagnosticCategory) {
DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
- DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message";
+ DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
+ DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
})(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
+ /* @internal */
+ function diagnosticCategoryName(d, lowerCase) {
+ if (lowerCase === void 0) { lowerCase = true; }
+ var name = DiagnosticCategory[d.category];
+ return lowerCase ? name.toLowerCase() : name;
+ }
+ ts.diagnosticCategoryName = diagnosticCategoryName;
var ModuleResolutionKind;
(function (ModuleResolutionKind) {
ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
@@ -1426,6 +1438,68 @@ var ts;
ListFormat[ListFormat["Parameters"] = 1296] = "Parameters";
ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters";
})(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
+ /* @internal */
+ var PragmaKindFlags;
+ (function (PragmaKindFlags) {
+ PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
+ /**
+ * Triple slash comment of the form
+ * ///
+ */
+ PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
+ /**
+ * Single line comment of the form
+ * // @pragma-name argval1 argval2
+ * or
+ * /// @pragma-name argval1 argval2
+ */
+ PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
+ /**
+ * Multiline non-jsdoc pragma of the form
+ * /* @pragma-name argval1 argval2 * /
+ */
+ PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
+ PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
+ PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
+ })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
+ /**
+ * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas`
+ */
+ /* @internal */
+ function _contextuallyTypePragmas(args) {
+ return args;
+ }
+ // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
+ // fancy effectively defining it twice, once in value-space and once in type-space
+ /* @internal */
+ ts.commentPragmas = _contextuallyTypePragmas({
+ "reference": {
+ args: [
+ { name: "types", optional: true, captureSpan: true },
+ { name: "path", optional: true, captureSpan: true },
+ { name: "no-default-lib", optional: true }
+ ],
+ kind: 1 /* TripleSlashXML */
+ },
+ "amd-dependency": {
+ args: [{ name: "path" }, { name: "name", optional: true }],
+ kind: 1 /* TripleSlashXML */
+ },
+ "amd-module": {
+ args: [{ name: "name" }],
+ kind: 1 /* TripleSlashXML */
+ },
+ "ts-check": {
+ kind: 2 /* SingleLine */
+ },
+ "ts-nocheck": {
+ kind: 2 /* SingleLine */
+ },
+ "jsx": {
+ args: [{ name: "factory" }],
+ kind: 4 /* MultiLine */
+ },
+ });
})(ts || (ts = {}));
/*@internal*/
var ts;
@@ -1528,7 +1602,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "2.8";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".0";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -2752,19 +2826,21 @@ var ts;
}
ts.equalOwnProperties = equalOwnProperties;
function arrayToMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = createMap();
for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
var value = array_6[_i];
- result.set(makeKey(value), makeValue ? makeValue(value) : value);
+ result.set(makeKey(value), makeValue(value));
}
return result;
}
ts.arrayToMap = arrayToMap;
function arrayToNumericMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = [];
for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
var value = array_7[_i];
- result[makeKey(value)] = makeValue ? makeValue(value) : value;
+ result[makeKey(value)] = makeValue(value);
}
return result;
}
@@ -2773,6 +2849,20 @@ var ts;
return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; });
}
ts.arrayToSet = arrayToSet;
+ function arrayToMultiMap(values, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
+ var result = createMultiMap();
+ for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
+ var value = values_1[_i];
+ result.add(makeKey(value), makeValue(value));
+ }
+ return result;
+ }
+ ts.arrayToMultiMap = arrayToMultiMap;
+ function group(values, getGroupId) {
+ return arrayFrom(arrayToMultiMap(values, getGroupId).values());
+ }
+ ts.group = group;
function cloneMap(map) {
var clone = createMap();
copyEntries(map, clone);
@@ -2830,15 +2920,6 @@ var ts;
}
}
}
- function group(values, getGroupId) {
- var groupIdToGroup = createMultiMap();
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- groupIdToGroup.add(getGroupId(value), value);
- }
- return arrayFrom(groupIdToGroup.values());
- }
- ts.group = group;
/**
* Tests whether a value is an array.
*/
@@ -2958,7 +3039,6 @@ var ts;
return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; });
}
ts.formatStringFromArgs = formatStringFromArgs;
- ts.localizedDiagnosticMessages = undefined;
function getLocaleSpecificMessage(message) {
return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
}
@@ -3884,7 +3964,7 @@ var ts;
// Sort the offsets array using either the literal or canonical path representations.
includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive);
var _loop_2 = function (includeBasePath) {
- if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
+ if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
basePaths.push(includeBasePath);
}
};
@@ -4289,7 +4369,7 @@ var ts;
ts.matchedText = matchedText;
/** Return the object corresponding to the best pattern to match `candidate`. */
function findBestPatternMatch(values, getPattern, candidate) {
- var matchedValue = undefined;
+ var matchedValue;
// use length of prefix as betterness criteria
var longestMatchPrefixLength = -1;
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
@@ -4393,7 +4473,7 @@ var ts;
*/
/* @internal */
function setStackTraceLimit() {
- if (Error.stackTraceLimit < 100) {
+ if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
Error.stackTraceLimit = 100;
}
}
@@ -4788,7 +4868,7 @@ var ts;
return stat.size;
}
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return 0;
},
exit: function (exitCode) {
@@ -5481,6 +5561,7 @@ var ts;
Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
+ Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
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}'."),
@@ -5552,7 +5633,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}'."),
- 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.Message, "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."),
+ 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}'."),
Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
@@ -5725,7 +5806,7 @@ var ts;
Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
- Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."),
+ Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
@@ -5769,6 +5850,7 @@ var ts;
Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."),
+ Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."),
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."),
@@ -5848,10 +5930,15 @@ var ts;
JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
+ JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
+ File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
+ This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
+ Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
+ JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
@@ -5892,6 +5979,9 @@ var ts;
Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
+ Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
+ Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
+ Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
};
})(ts || (ts = {}));
///
@@ -8162,8 +8252,7 @@ var ts;
}
ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
function isAmbientModule(node) {
- return node && node.kind === 237 /* ModuleDeclaration */ &&
- (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
+ return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
}
ts.isAmbientModule = isAmbientModule;
function isModuleWithStringLiteralName(node) {
@@ -8194,21 +8283,22 @@ var ts;
}
ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
function isExternalModuleAugmentation(node) {
+ return isAmbientModule(node) && isModuleAugmentationExternal(node);
+ }
+ ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ function isModuleAugmentationExternal(node) {
// external module augmentation is a ambient module declaration that is either:
// - 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
- if (!node || !isAmbientModule(node)) {
- return false;
- }
switch (node.parent.kind) {
case 272 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 238 /* ModuleBlock */:
- return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
+ return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
}
return false;
}
- ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
function isEffectiveExternalModule(node, compilerOptions) {
return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
}
@@ -9524,16 +9614,9 @@ var ts;
return false;
}
ts.isNodeDescendantOf = isNodeDescendantOf;
- // True if the given identifier, string literal, or number literal is the name of a declaration node
+ // True if `name` is the name of a declaration node
function isDeclarationName(name) {
- switch (name.kind) {
- case 71 /* Identifier */:
- case 9 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- return ts.isDeclaration(name.parent) && name.parent.name === name;
- default:
- return false;
- }
+ return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
}
ts.isDeclarationName = isDeclarationName;
// See GH#16030
@@ -9660,38 +9743,6 @@ var ts;
return undefined;
}
ts.getAncestor = getAncestor;
- function getFileReferenceFromReferencePath(comment, commentRange) {
- var simpleReferenceRegEx = /^\/\/\/\s*= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
}
ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
function textSpanIntersectsWith(span, start, length) {
- var end = start + length;
- return start <= textSpanEnd(span) && end >= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
}
ts.textSpanIntersectsWith = textSpanIntersectsWith;
function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
@@ -11361,12 +11400,9 @@ var ts;
}
ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
function textSpanIntersection(span1, span2) {
- var intersectStart = Math.max(span1.start, span2.start);
- var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
- if (intersectStart <= intersectEnd) {
- return createTextSpanFromBounds(intersectStart, intersectEnd);
- }
- return undefined;
+ var start = Math.max(span1.start, span2.start);
+ var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
+ return start <= end ? createTextSpanFromBounds(start, end) : undefined;
}
ts.textSpanIntersection = textSpanIntersection;
function createTextSpan(start, length) {
@@ -11631,6 +11667,7 @@ var ts;
return false;
}
try {
+ // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!)
ts.localizedDiagnosticMessages = JSON.parse(fileContents);
}
catch (e) {
@@ -12958,7 +12995,7 @@ var ts;
case 97 /* SuperKeyword */:
case 207 /* NonNullExpression */:
case 208 /* MetaProperty */:
- case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression
+ case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
return true;
default:
return false;
@@ -13043,7 +13080,6 @@ var ts;
|| isPartiallyEmittedExpression(node);
}
ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
- // Statement
function isIterationStatement(node, lookInLabeledStatements) {
switch (node.kind) {
case 218 /* ForStatement */:
@@ -14099,7 +14135,9 @@ var ts;
sourceFile.flags = contextFlags;
// Prime the scanner.
nextToken();
- processReferenceComments(sourceFile);
+ // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future
+ processCommentPragmas(sourceFile, sourceText);
+ processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
ts.Debug.assert(token() === 1 /* EndOfFileToken */);
sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
@@ -14112,6 +14150,9 @@ var ts;
fixupParentReferences(sourceFile);
}
return sourceFile;
+ function reportPragmaDiagnostic(pos, end, diagnostic) {
+ parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
+ }
}
function addJSDocComment(node) {
var comments = ts.getJSDocCommentRanges(node, sourceFile.text);
@@ -17089,8 +17130,9 @@ var ts;
var fullStart = scanner.getStartPos();
parseExpected(27 /* LessThanToken */);
if (token() === 29 /* GreaterThanToken */) {
- parseExpected(29 /* GreaterThanToken */);
+ // See below for explanation of scanJsxText
var node_1 = createNode(258 /* JsxOpeningFragment */, fullStart);
+ scanJsxText();
return finishNode(node_1);
}
var tagName = parseJsxElementName();
@@ -17137,7 +17179,9 @@ var ts;
}
function parseJsxExpression(inExpressionContext) {
var node = createNode(263 /* JsxExpression */);
- parseExpected(17 /* OpenBraceToken */);
+ if (!parseExpected(17 /* OpenBraceToken */)) {
+ return undefined;
+ }
if (token() !== 18 /* CloseBraceToken */) {
node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
node.expression = parseAssignmentExpressionOrHigher();
@@ -17332,7 +17376,7 @@ var ts;
case 48 /* AmpersandToken */: // foo &
case 49 /* BarToken */: // foo |
case 18 /* CloseBraceToken */: // foo }
- case 1 /* EndOfFileToken */:// foo
+ case 1 /* EndOfFileToken */: // foo
// these cases can't legally follow a type arg list. However, they're not legal
// expressions either. The user is probably in the middle of a generic type. So
// treat it as such.
@@ -17601,7 +17645,7 @@ var ts;
parseExpected(88 /* ForKeyword */);
var awaitToken = parseOptionalToken(121 /* AwaitKeyword */);
parseExpected(19 /* OpenParenToken */);
- var initializer = undefined;
+ var initializer;
if (token() !== 25 /* SemicolonToken */) {
if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) {
initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
@@ -18302,7 +18346,7 @@ var ts;
case 51 /* ExclamationToken */: // Non-null assertion on property name
case 56 /* ColonToken */: // Type Annotation for declaration
case 58 /* EqualsToken */: // Initializer for declaration
- case 55 /* QuestionToken */:// Not valid, but permitted so that it gets caught later on.
+ case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
return true;
default:
// Covers
@@ -18617,7 +18661,7 @@ var ts;
// import ModuleSpecifier;
if (identifier || // import id
token() === 39 /* AsteriskToken */ || // import *
- token() === 17 /* OpenBraceToken */) {
+ token() === 17 /* OpenBraceToken */) { // import {
node.importClause = parseImportClause(identifier, afterImportPos);
parseExpected(142 /* FromKeyword */);
}
@@ -18767,87 +18811,6 @@ var ts;
parseSemicolon();
return finishNode(node);
}
- function processReferenceComments(sourceFile) {
- var triviaScanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText);
- var referencedFiles = [];
- var typeReferenceDirectives = [];
- var amdDependencies = [];
- var amdModuleName;
- var checkJsDirective = undefined;
- // Keep scanning all the leading trivia in the file until we get to something that
- // isn't trivia. Any single line comment will be analyzed to see if it is a
- // reference comment.
- while (true) {
- var kind = triviaScanner.scan();
- if (kind !== 2 /* SingleLineCommentTrivia */) {
- if (ts.isTrivia(kind)) {
- continue;
- }
- else {
- break;
- }
- }
- var range = {
- kind: triviaScanner.getToken(),
- pos: triviaScanner.getTokenPos(),
- end: triviaScanner.getTextPos(),
- };
- var comment = sourceText.substring(range.pos, range.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range);
- if (referencePathMatchResult) {
- var fileReference = referencePathMatchResult.fileReference;
- sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var diagnosticMessage = referencePathMatchResult.diagnosticMessage;
- if (fileReference) {
- if (referencePathMatchResult.isTypeReferenceDirective) {
- typeReferenceDirectives.push(fileReference);
- }
- else {
- referencedFiles.push(fileReference);
- }
- }
- if (diagnosticMessage) {
- parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage));
- }
- }
- else {
- var amdModuleNameRegEx = /^\/\/\/\s* context.checkJsDirective.pos) {
+ context.checkJsDirective = {
+ enabled: key === "ts-check",
+ end: entry.range.end,
+ pos: entry.range.pos
+ };
+ }
+ });
+ break;
+ }
+ case "jsx": return; // Accessed directly
+ default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
+ }
+ });
+ }
+ ts.processPragmasIntoFields = processPragmasIntoFields;
+ var namedArgRegExCache = ts.createMap();
+ function getNamedArgRegEx(name) {
+ if (namedArgRegExCache.has(name)) {
+ return namedArgRegExCache.get(name);
+ }
+ var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
+ namedArgRegExCache.set(name, result);
+ return result;
+ }
+ var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
+ var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
+ function extractPragmas(pragmas, range, text) {
+ var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text);
+ if (tripleSlash) {
+ var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
+ return;
+ }
+ if (pragma.args) {
+ var argument = {};
+ for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
+ var arg = _a[_i];
+ var matcher = getNamedArgRegEx(arg.name);
+ var matchResult = matcher.exec(text);
+ if (!matchResult && !arg.optional) {
+ return; // Missing required argument, don't parse
+ }
+ else if (matchResult) {
+ if (arg.captureSpan) {
+ var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
+ argument[arg.name] = {
+ value: matchResult[3],
+ pos: startPos,
+ end: startPos + matchResult[3].length
+ };
+ }
+ else {
+ argument[arg.name] = matchResult[3];
+ }
+ }
+ }
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ }
+ else {
+ pragmas.push({ name: name, args: { arguments: {}, range: range } });
+ }
+ return;
+ }
+ var singleLine = singleLinePragmaRegEx.exec(text);
+ if (singleLine) {
+ return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
+ }
+ var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
+ var multiLineMatch;
+ while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
+ addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
+ }
+ }
+ function addPragmaForMatch(pragmas, range, kind, match) {
+ if (!match)
+ return;
+ var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & kind)) {
+ return;
+ }
+ var args = match[2]; // Split on spaces and match up positionally with definition
+ var argument = getNamedPragmaArguments(pragma, args);
+ if (argument === "fail")
+ return; // Missing required argument, fail to parse it
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ return;
+ }
+ function getNamedPragmaArguments(pragma, text) {
+ if (!text)
+ return {};
+ if (!pragma.args)
+ return {};
+ var args = text.split(/\s+/);
+ var argMap = {};
+ for (var i = 0; i < pragma.args.length; i++) {
+ var argument = pragma.args[i];
+ if (!args[i] && !argument.optional) {
+ return "fail";
+ }
+ if (argument.captureSpan) {
+ return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
+ }
+ argMap[argument.name] = args[i];
+ }
+ return argMap;
+ }
})(ts || (ts = {}));
///
///
@@ -20299,7 +20465,7 @@ var ts;
ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
}
- return ts.getEscapedTextOfIdentifierOrLiteral(name);
+ return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
switch (node.kind) {
case 154 /* Constructor */:
@@ -20440,7 +20606,12 @@ var ts;
}
}
addDeclarationToSymbol(symbol, node, includes);
- symbol.parent = parent;
+ if (symbol.parent) {
+ ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ symbol.parent = parent;
+ }
return symbol;
}
function declareModuleMember(node, symbolFlags, symbolExcludes) {
@@ -21529,7 +21700,7 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
- if (ts.isExternalModuleAugmentation(node)) {
+ if (ts.isModuleAugmentationExternal(node)) {
declareModuleSymbol(node);
}
else {
@@ -21544,9 +21715,7 @@ var ts;
}
}
var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
- if (pattern) {
- (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol });
- }
+ file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
}
}
else {
@@ -21951,7 +22120,7 @@ var ts;
seenThisKeyword = true;
return;
case 160 /* TypePredicate */:
- return checkTypePredicate(node);
+ break; // Binding the children will handle everything
case 147 /* TypeParameter */:
return bindTypeParameter(node);
case 148 /* Parameter */:
@@ -22075,16 +22244,6 @@ var ts;
function bindAnonymousTypeWorker(node) {
return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
}
- function checkTypePredicate(node) {
- var parameterName = node.parameterName, type = node.type;
- if (parameterName && parameterName.kind === 71 /* Identifier */) {
- checkStrictModeIdentifier(parameterName);
- }
- if (parameterName && parameterName.kind === 173 /* ThisType */) {
- seenThisKeyword = true;
- }
- bind(type);
- }
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (ts.isExternalModule(file)) {
@@ -23757,8 +23916,11 @@ var ts;
}
ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
- var directoryToModuleNameMap = ts.createMap();
- var moduleNameToDirectoryMap = ts.createMap();
+ return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName);
+ }
+ ts.createModuleResolutionCache = createModuleResolutionCache;
+ /*@internal*/
+ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
function getOrCreateCacheForDirectory(directoryName) {
var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
@@ -23842,7 +24004,7 @@ var ts;
}
}
}
- ts.createModuleResolutionCache = createModuleResolutionCache;
+ ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
@@ -23853,7 +24015,7 @@ var ts;
var result = perFolderCache && perFolderCache.get(moduleName);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
}
else {
@@ -24043,7 +24205,7 @@ var ts;
trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
}
// string is for exact match
- var matchedPattern = undefined;
+ var matchedPattern;
if (state.compilerOptions.paths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
@@ -24319,7 +24481,7 @@ var ts;
var packageJsonPath = pathToPackageJson(nodeModuleDirectory);
if (directoryExists && host.fileExists(packageJsonPath)) {
var packageJsonContent = readJson(packageJsonPath, host);
- if (subModuleName === "") {
+ if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName
var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state);
if (typeof path === "string") {
subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1));
@@ -24415,7 +24577,7 @@ var ts;
}
else {
var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
- if (rest !== "") {
+ if (rest !== "") { // If "rest" is empty, we just did this search above.
var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName);
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId.
packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId;
@@ -24492,6 +24654,7 @@ var ts;
return "@types/" + getMangledNameForScopedPackage(packageName);
}
ts.getTypesPackageName = getTypesPackageName;
+ /* @internal */
function getMangledNameForScopedPackage(packageName) {
if (ts.startsWith(packageName, "@")) {
var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
@@ -24501,6 +24664,7 @@ var ts;
}
return packageName;
}
+ ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage;
/* @internal */
function getPackageNameFromAtTypesDirectory(mangledName) {
var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
@@ -24521,7 +24685,7 @@ var ts;
var result = cache && cache.get(containingDirectory);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
}
@@ -24828,7 +24992,7 @@ var ts;
node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement);
return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined;
},
- getJsxIntrinsicTagNames: getJsxIntrinsicTagNames,
+ getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
isOptionalParameter: function (node) {
node = ts.getParseTreeNode(node, ts.isParameter);
return node ? isOptionalParameter(node) : false;
@@ -24867,7 +25031,7 @@ var ts;
resolveName: function (name, location, meaning, excludeGlobals) {
return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
},
- getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); },
+ getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
@@ -24879,13 +25043,13 @@ var ts;
node = ts.getParseTreeNode(node, ts.isTypeNode);
return node && getTypeArgumentConstraint(node);
},
+ getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; },
};
var tupleTypes = [];
var unionTypes = ts.createMap();
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
- var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4 /* Property */, "unknown");
@@ -24954,6 +25118,7 @@ var ts;
var anyArrayType;
var autoArrayType;
var anyReadonlyArrayType;
+ var deferredGlobalNonNullableTypeAlias;
// The library files are only loaded when the feature is used.
// 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
@@ -24970,9 +25135,6 @@ var ts;
var deferredGlobalAsyncIteratorType;
var deferredGlobalAsyncIterableIteratorType;
var deferredGlobalTemplateStringsArrayType;
- var deferredJsxElementClassType;
- var deferredJsxElementType;
- var deferredJsxStatelessElementType;
var deferredNodes;
var deferredUnusedIdentifierNodes;
var flowLoopStart = 0;
@@ -24999,6 +25161,19 @@ var ts;
var potentialNewTargetCollisions = [];
var awaitedTypeStack = [];
var diagnostics = ts.createDiagnosticCollection();
+ // Suggestion diagnostics must have a file. Keyed by source file name.
+ var suggestionDiagnostics = ts.createMultiMap();
+ function addSuggestionDiagnostic(diag) {
+ suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
+ }
+ function addErrorOrSuggestionDiagnostic(isError, diag) {
+ if (isError) {
+ diagnostics.add(diag);
+ }
+ else {
+ addSuggestionDiagnostic(diag);
+ }
+ }
var TypeFacts;
(function (TypeFacts) {
TypeFacts[TypeFacts["None"] = 0] = "None";
@@ -25024,8 +25199,7 @@ var ts;
TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull";
TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy";
TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy";
- TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable";
- TypeFacts[TypeFacts["All"] = 8388607] = "All";
+ TypeFacts[TypeFacts["All"] = 4194303] = "All";
// The following members encode facts about particular kinds of types for use in the getTypeFacts function.
// The presence of a particular fact means that the given test is true for some (and possibly all) values
// of that kind of type.
@@ -25055,10 +25229,10 @@ var ts;
TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts";
TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts";
TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts";
- TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts";
- TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts";
- TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts";
- TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts";
+ TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts";
+ TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts";
+ TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts";
+ TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts";
TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts";
TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts";
})(TypeFacts || (TypeFacts = {}));
@@ -25090,12 +25264,6 @@ var ts;
var typeofType = createTypeofType();
var _jsxNamespace;
var _jsxFactoryEntity;
- var _jsxElementPropertiesName;
- var _hasComputedJsxElementPropertiesName = false;
- var _jsxElementChildrenPropertyName;
- var _hasComputedJsxElementChildrenPropertyName = false;
- /** Things we lazy load from the JSX namespace */
- var jsxTypes = ts.createUnderscoreEscapedMap();
var subtypeRelation = ts.createMap();
var assignableRelation = ts.createMap();
var definitelyAssignableRelation = ts.createMap();
@@ -25151,6 +25319,7 @@ var ts;
TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType";
TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject";
TypeIncludes[TypeIncludes["Union"] = 2048] = "Union";
+ TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard";
})(TypeIncludes || (TypeIncludes = {}));
var MembersOrExportsResolutionKind;
(function (MembersOrExportsResolutionKind) {
@@ -25298,7 +25467,23 @@ var ts;
};
}
}
- function getJsxNamespace() {
+ function getJsxNamespace(location) {
+ if (location) {
+ var file = ts.getSourceFileOfNode(location);
+ if (file) {
+ if (file.localJsxNamespace) {
+ return file.localJsxNamespace;
+ }
+ var jsxPragma = file.pragmas.get("jsx");
+ if (jsxPragma) {
+ var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
+ file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
+ if (file.localJsxFactory) {
+ return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
+ }
+ }
+ }
+ }
if (!_jsxNamespace) {
_jsxNamespace = "React";
if (compilerOptions.jsxFactory) {
@@ -25982,7 +26167,7 @@ var ts;
case 234 /* InterfaceDeclaration */:
case 236 /* EnumDeclaration */:
case 235 /* TypeAliasDeclaration */:
- case 237 /* ModuleDeclaration */:// For `namespace N { N; }`
+ case 237 /* ModuleDeclaration */: // For `namespace N { N; }`
return true;
default:
return false;
@@ -26294,7 +26479,15 @@ var ts;
combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
symbolFromModule || symbolFromVariable;
if (!symbol) {
- error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name));
+ var moduleName = getFullyQualifiedName(moduleSymbol);
+ var declarationName = ts.declarationNameToString(name);
+ var suggestion = getSuggestionForNonexistentModule(name, targetSymbol);
+ if (suggestion !== undefined) {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion);
+ }
+ else {
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
+ }
}
return symbol;
}
@@ -26505,6 +26698,9 @@ var ts;
var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
+ if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) {
+ addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
+ }
// merged symbol is module declaration symbol combined with all augmentations
return getMergedSymbol(sourceFile.symbol);
}
@@ -26526,10 +26722,8 @@ var ts;
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
}
- else if (noImplicitAny && moduleNotFoundError) {
- var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name);
- errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName);
- diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo));
+ else {
+ addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference));
}
// Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
return undefined;
@@ -26552,6 +26746,12 @@ var ts;
}
return undefined;
}
+ function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) {
+ var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
+ var errorInfo = packageId && ts.chainDiagnosticMessages(
+ /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name));
+ return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
+ }
// An external module with an 'export =' declaration resolves to the target of the 'export =' declaration,
// and an external module with no 'export =' declaration resolves to the module itself.
function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
@@ -26829,11 +27029,19 @@ var ts;
// If we are looking in value space, the parent meaning is value, other wise it is namespace
return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */;
}
- function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) {
+ function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
+ if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
return undefined;
}
- var visitedSymbolTables = [];
+ var id = "" + getSymbolId(symbol);
+ var visitedSymbolTables;
+ if (visitedSymbolTablesMap.has(id)) {
+ visitedSymbolTables = visitedSymbolTablesMap.get(id);
+ }
+ else {
+ visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
+ }
return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
/**
* @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)
@@ -26850,7 +27058,7 @@ var ts;
// If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
// If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
- !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing);
+ !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
}
function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) &&
@@ -26868,7 +27076,8 @@ var ts;
// Check if symbol is any of the alias
return ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
if (symbolFromSymbolTable.flags & 2097152 /* Alias */
- && symbolFromSymbolTable.escapedName !== "export="
+ && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
+ && symbolFromSymbolTable.escapedName !== "default" /* Default */
&& !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
// If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
&& (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) {
@@ -27105,6 +27314,7 @@ var ts;
}
}
function typeToString(type, enclosingDeclaration, flags, writer) {
+ if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; }
if (writer === void 0) { writer = ts.createTextWriter(""); }
var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer);
ts.Debug.assert(typeNode !== undefined, "should always get typenode");
@@ -27230,6 +27440,9 @@ var ts;
}
if (type.flags & 1024 /* UniqueESSymbol */) {
if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
+ if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
+ return ts.createTypeQueryNode(symbolToName(type.symbol, context, 107455 /* Value */, /*expectsIdentifier*/ false));
+ }
if (context.tracker.reportInaccessibleUniqueSymbolError) {
context.tracker.reportInaccessibleUniqueSymbolError();
}
@@ -27312,8 +27525,8 @@ var ts;
if (type.flags & 2097152 /* Conditional */) {
var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
- var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
- var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
+ var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
+ var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
if (type.flags & 4194304 /* Substitution */) {
@@ -27482,7 +27695,7 @@ var ts;
}
}
}
- var entityName = undefined;
+ var entityName = void 0;
var nameIdentifier = symbolToTypeReferenceName(type.symbol);
if (qualifiedName) {
ts.Debug.assert(!qualifiedName.right);
@@ -27936,8 +28149,8 @@ var ts;
return "(Anonymous function)";
}
}
- if (symbol.syntheticLiteralTypeOrigin) {
- var stringValue = symbol.syntheticLiteralTypeOrigin.value;
+ if (symbol.nameType && symbol.nameType.flags & 32 /* StringLiteral */) {
+ var stringValue = symbol.nameType.value;
if (!ts.isIdentifierText(stringValue, compilerOptions.target)) {
return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\"";
}
@@ -28245,7 +28458,7 @@ var ts;
parentType = getNonNullableType(parentType);
}
var propType = getTypeOfPropertyOfType(parentType, text);
- var declaredType = propType && getApparentTypeForLocation(propType, declaration.name);
+ var declaredType = propType && getConstraintForLocation(propType, declaration.name);
type = declaredType && getFlowTypeOfReference(declaration, declaredType) ||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
getIndexTypeOfType(parentType, 0 /* String */);
@@ -28677,6 +28890,7 @@ var ts;
if (getter && getter.body) {
type = getReturnTypeFromBody(getter);
}
+ // Otherwise, fall back to 'any'.
else {
if (noImplicitAny) {
if (setter) {
@@ -29548,8 +29762,18 @@ var ts;
error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3);
lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */);
}
+ var symbolLinks_1 = getSymbolLinks(lateSymbol);
+ if (!symbolLinks_1.nameType) {
+ // Retain link to name type so that it can be reused later
+ symbolLinks_1.nameType = type;
+ }
addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
- lateSymbol.parent = parent;
+ if (lateSymbol.parent) {
+ ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
+ }
+ else {
+ lateSymbol.parent = parent;
+ }
return links.resolvedSymbol = lateSymbol;
}
}
@@ -29751,7 +29975,7 @@ var ts;
}
return [signature];
}
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
// Allow matching non-generic signatures to have excess parameters and different return types
var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true);
@@ -29768,7 +29992,7 @@ var ts;
// type is the union of the constituent return types.
function getUnionSignatures(types, kind) {
var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); });
- var result = undefined;
+ var result;
for (var i = 0; i < signatureLists.length; i++) {
for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
var signature = _a[_i];
@@ -29899,7 +30123,7 @@ var ts;
else {
// Combinations of function, class, enum and module
var members = emptySymbols;
- var stringIndexInfo = undefined;
+ var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
}
@@ -29998,13 +30222,12 @@ var ts;
// Create a mapper from T to the current iteration type constituent. Then, if the
// mapped type is itself an instantiated type, combine the iteration mapper with the
// instantiation mapper.
- var iterationMapper = createTypeMapper([typeParameter], [t]);
- var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper;
+ var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t]));
var propType = instantiateType(templateType, templateMapper);
// If the current iteration type constituent is a string literal type, create a property.
// Otherwise, for type string create a string index signature.
if (t.flags & 32 /* StringLiteral */) {
- var propName = ts.escapeLeadingUnderscores(t.value);
+ var propName = getLateBoundNameFromType(t);
var modifiersProp = getPropertyOfType(modifiersType, propName);
var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
!(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
@@ -30021,7 +30244,7 @@ var ts;
prop.syntheticOrigin = propertySymbol;
prop.declarations = propertySymbol.declarations;
}
- prop.syntheticLiteralTypeOrigin = t;
+ prop.nameType = t;
members.set(propName, prop);
}
else if (t.flags & (1 /* Any */ | 2 /* String */)) {
@@ -30206,7 +30429,7 @@ var ts;
return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined;
}
function getDefaultConstraintOfConditionalType(type) {
- return getUnionType([type.trueType, type.falseType]);
+ return getUnionType([getTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]);
}
function getConstraintOfDistributiveConditionalType(type) {
// Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
@@ -30214,13 +30437,11 @@ var ts;
// with its constraint. We do this because if the constraint is a union type it will be distributed
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
- if (isDistributiveConditionalType(type)) {
+ if (type.root.isDistributive) {
var constraint = getConstraintOfType(type.checkType);
if (constraint) {
- var target = type.target || type;
- var mapper = createTypeMapper([target.checkType], [constraint]);
- var combinedMapper = type.mapper ? combineTypeMappers(mapper, type.mapper) : mapper;
- return instantiateType(target, combinedMapper);
+ var mapper = createTypeMapper([type.root.checkType], [constraint]);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
}
}
return undefined;
@@ -30228,17 +30449,27 @@ var ts;
function getConstraintOfConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
- function getBaseConstraintOfType(type) {
+ function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) {
if (type.flags & (7372800 /* InstantiableNonPrimitive */ | 393216 /* UnionOrIntersection */)) {
var constraint = getResolvedBaseConstraint(type);
if (constraint !== noConstraintType && constraint !== circularConstraintType) {
return constraint;
}
}
- else if (type.flags & 524288 /* Index */) {
+ }
+ function getBaseConstraintOfType(type) {
+ var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type);
+ if (!constraint && type.flags & 524288 /* Index */) {
return stringType;
}
- return undefined;
+ return constraint;
+ }
+ /**
+ * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
+ * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
+ */
+ function getBaseConstraintOrType(type) {
+ return getBaseConstraintOfType(type) || type;
}
function hasNonCircularBaseConstraint(type) {
return getResolvedBaseConstraint(type) !== circularConstraintType;
@@ -30302,7 +30533,8 @@ var ts;
return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 2097152 /* Conditional */) {
- return getBaseConstraint(getConstraintOfConditionalType(t));
+ var constraint = getConstraintOfConditionalType(t);
+ return constraint && getBaseConstraint(constraint);
}
if (t.flags & 4194304 /* Substitution */) {
return getBaseConstraint(t.substitute);
@@ -30413,7 +30645,7 @@ var ts;
}
var propTypes = [];
var declarations = [];
- var commonType = undefined;
+ var commonType;
for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
var prop = props_1[_b];
if (prop.declarations) {
@@ -30670,7 +30902,7 @@ var ts;
var parameters = [];
var hasLiteralTypes = false;
var minArgumentCount = 0;
- var thisParameter = undefined;
+ var thisParameter = void 0;
var hasThisParameter = void 0;
var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
@@ -31197,6 +31429,7 @@ var ts;
if (ts.isEntityNameExpression(expr)) {
return expr;
}
+ // fall through;
}
return undefined;
}
@@ -31452,15 +31685,6 @@ var ts;
var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined);
return symbol && getTypeOfGlobalSymbol(symbol, arity);
}
- /**
- * Returns a type that is inside a namespace at the global scope, e.g.
- * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type
- */
- function getExportedTypeFromNamespace(namespace, name) {
- var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined);
- var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */);
- return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol);
- }
/**
* Instantiates a global type that is generic with some element type, and returns that instantiation.
*/
@@ -31572,6 +31796,8 @@ var ts;
}
else if (flags & 1 /* Any */) {
includes |= 1 /* Any */;
+ if (type === wildcardType)
+ includes |= 4096 /* Wildcard */;
}
else if (!strictNullChecks && flags & 12288 /* Nullable */) {
if (flags & 4096 /* Undefined */)
@@ -31692,7 +31918,7 @@ var ts;
var typeSet = [];
var includes = addTypesToUnion(typeSet, 0, types);
if (includes & 1 /* Any */) {
- return anyType;
+ return includes & 4096 /* Wildcard */ ? wildcardType : anyType;
}
switch (unionReduction) {
case 1 /* Literal */:
@@ -31785,6 +32011,8 @@ var ts;
}
else if (flags & 1 /* Any */) {
includes |= 1 /* Any */;
+ if (type === wildcardType)
+ includes |= 4096 /* Wildcard */;
}
else if (flags & 16384 /* Never */) {
includes |= 8 /* Never */;
@@ -31835,7 +32063,7 @@ var ts;
return neverType;
}
if (includes & 1 /* Any */) {
- return anyType;
+ return includes & 4096 /* Wildcard */ ? wildcardType : anyType;
}
if (includes & 1024 /* EmptyObject */ && !(includes & 512 /* ObjectType */)) {
typeSet.push(emptyObjectType);
@@ -31877,19 +32105,30 @@ var ts;
return type.resolvedIndexType;
}
function getLiteralTypeFromPropertyName(prop) {
- return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ?
- neverType :
- getLiteralType(ts.symbolName(prop));
+ var links = getSymbolLinks(prop);
+ if (!links.nameType) {
+ if (links.target) {
+ ts.Debug.assert(links.target.escapedName === prop.escapedName, "Target symbol and symbol do not have the same name");
+ links.nameType = getLiteralTypeFromPropertyName(links.target);
+ }
+ else {
+ links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ?
+ neverType :
+ getLiteralType(ts.symbolName(prop));
+ }
+ }
+ return links.nameType;
}
function getLiteralTypeFromPropertyNames(type) {
return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName));
}
function getIndexType(type) {
- return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) :
- ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) :
- type === wildcardType ? wildcardType :
- type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType :
- getLiteralTypeFromPropertyNames(type);
+ return type.flags & 262144 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) :
+ maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) :
+ ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) :
+ type === wildcardType ? wildcardType :
+ type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType :
+ getLiteralTypeFromPropertyNames(type);
}
function getIndexTypeOrString(type) {
var indexType = getIndexType(type);
@@ -32050,10 +32289,13 @@ var ts;
}
function substituteIndexedMappedType(objectType, type) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper;
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
}
function getIndexedAccessType(objectType, indexType, accessNode) {
+ if (objectType === wildcardType || indexType === wildcardType) {
+ return wildcardType;
+ }
// If the index type is generic, or if the object type is generic and doesn't originate in an expression,
// we are performing a higher-order index access where we cannot meaningfully access the properties of the
// object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
@@ -32113,73 +32355,62 @@ var ts;
function getActualTypeParameter(type) {
return type.flags & 4194304 /* Substitution */ ? type.typeParameter : type;
}
- function createConditionalType(checkType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, aliasTypeArguments) {
- var type = createType(2097152 /* Conditional */);
- type.checkType = checkType;
- type.extendsType = extendsType;
- type.trueType = trueType;
- type.falseType = falseType;
- type.inferTypeParameters = inferTypeParameters;
- type.target = target;
- type.mapper = mapper;
- type.aliasSymbol = aliasSymbol;
- type.aliasTypeArguments = aliasTypeArguments;
- return type;
- }
- function getConditionalType(checkType, baseExtendsType, baseTrueType, baseFalseType, inferTypeParameters, target, mapper, aliasSymbol, baseAliasTypeArguments) {
- // Instantiate extends type without instantiating any 'infer T' type parameters
- var extendsType = instantiateType(baseExtendsType, mapper);
- // Return falseType for a definitely false extends check. We check an instantations 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 instatiations will be and we can just return the false branch type.
- if (!typeMaybeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(extendsType))) {
- return instantiateType(baseFalseType, mapper);
+ function getConditionalType(root, mapper) {
+ var checkType = instantiateType(root.checkType, mapper);
+ var extendsType = instantiateType(root.extendsType, mapper);
+ if (checkType === wildcardType || extendsType === wildcardType) {
+ return wildcardType;
}
- // The check could be true for some instantiation
- var combinedMapper;
- if (inferTypeParameters) {
- var inferences = ts.map(inferTypeParameters, createInferenceInfo);
- // 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(inferences, checkType, extendsType, 8 /* NoConstraints */ | 16 /* AlwaysStrict */);
- // We infer 'never' when there are no candidates for a type parameter
- var inferredTypes = ts.map(inferences, function (inference) { return getTypeFromInference(inference) || neverType; });
- var inferenceMapper = createTypeMapper(inferTypeParameters, inferredTypes);
- combinedMapper = mapper ? combineTypeMappers(mapper, inferenceMapper) : inferenceMapper;
- }
- // Return union of trueType and falseType for any and never since they match anything
- if (checkType.flags & 1 /* Any */ || (checkType.flags & 16384 /* Never */ && !(extendsType.flags & 16384 /* Never */))) {
- return getUnionType([instantiateType(baseTrueType, combinedMapper || mapper), instantiateType(baseFalseType, mapper)]);
- }
- // Instantiate the extends type including inferences for 'infer T' type parameters
- var inferredExtendsType = combinedMapper ? instantiateType(baseExtendsType, combinedMapper) : extendsType;
- // Return trueType for a definitely true extends check. The definitely assignable relation excludes
- // type variable constraints from consideration. Without the definitely assignable relation, the type
- // type Foo = T extends { x: string } ? string : number
- // would immediately resolve to 'string' instead of being deferred.
- if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) {
- return instantiateType(baseTrueType, combinedMapper || mapper);
+ // If this is a distributive conditional type and the check type is generic we need to defer
+ // resolution of the conditional type such that a later instantiation will properly distribute
+ // over union types.
+ if (!root.isDistributive || !maybeTypeOfKind(checkType, 7897088 /* Instantiable */)) {
+ var combinedMapper = void 0;
+ if (root.inferTypeParameters) {
+ var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
+ // 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, 16 /* NoConstraints */ | 32 /* AlwaysStrict */);
+ combinedMapper = combineTypeMappers(mapper, context);
+ }
+ // Return union of trueType and falseType for 'any' since it matches anything
+ if (checkType.flags & 1 /* Any */) {
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ }
+ // Instantiate the extends type including inferences for 'infer T' type parameters
+ var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
+ // Return falseType for a definitely false extends check. We check an instantations 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 instatiations will be and we can just return the false branch type.
+ if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) {
+ return instantiateType(root.falseType, mapper);
+ }
+ // Return trueType for a definitely true extends check. The definitely assignable relation excludes
+ // type variable constraints from consideration. Without the definitely assignable relation, the type
+ // type Foo = T extends { x: string } ? string : number
+ // would immediately resolve to 'string' instead of being deferred.
+ if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) {
+ return instantiateType(root.trueType, combinedMapper || mapper);
+ }
}
// Return a deferred type for a check that is neither definitely true nor definitely false
var erasedCheckType = getActualTypeParameter(checkType);
- var trueType = instantiateType(baseTrueType, mapper);
- var falseType = instantiateType(baseFalseType, mapper);
- // We compute the cache key from the ids of the four constituent types, plus an indicator of whether the
- // type is distributive (i.e. whether the original declaration has a type parameter as the check type).
- var isDistributive = (target ? target.checkType : erasedCheckType).flags & 32768 /* TypeParameter */ ? 1 : 0;
- var id = erasedCheckType.id + "," + extendsType.id + "," + trueType.id + "," + falseType.id + "," + isDistributive;
- var cached = conditionalTypes.get(id);
- if (cached) {
- return cached;
- }
- var result = createConditionalType(erasedCheckType, extendsType, trueType, falseType, inferTypeParameters, target, mapper, aliasSymbol, instantiateTypes(baseAliasTypeArguments, mapper));
- conditionalTypes.set(id, result);
+ var result = createType(2097152 /* Conditional */);
+ result.root = root;
+ result.checkType = erasedCheckType;
+ result.extendsType = extendsType;
+ result.mapper = mapper;
+ result.aliasSymbol = root.aliasSymbol;
+ result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper);
return result;
}
- function isDistributiveConditionalType(type) {
- return !!((type.target || type).checkType.flags & 32768 /* TypeParameter */);
+ function getTrueTypeFromConditionalType(type) {
+ return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
+ }
+ function getFalseTypeFromConditionalType(type) {
+ return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -32195,7 +32426,28 @@ var ts;
function getTypeFromConditionalTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getConditionalType(getTypeFromTypeNode(node.checkType), getTypeFromTypeNode(node.extendsType), getTypeFromTypeNode(node.trueType), getTypeFromTypeNode(node.falseType), getInferTypeParameters(node), /*target*/ undefined, /*mapper*/ undefined, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node));
+ var checkType = getTypeFromTypeNode(node.checkType);
+ var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
+ var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
+ var root = {
+ node: node,
+ checkType: checkType,
+ extendsType: getTypeFromTypeNode(node.extendsType),
+ trueType: getTypeFromTypeNode(node.trueType),
+ falseType: getTypeFromTypeNode(node.falseType),
+ isDistributive: !!(checkType.flags & 32768 /* TypeParameter */),
+ inferTypeParameters: getInferTypeParameters(node),
+ outerTypeParameters: outerTypeParameters,
+ instantiations: undefined,
+ aliasSymbol: getAliasSymbolForTypeNode(node),
+ aliasTypeArguments: aliasTypeArguments
+ };
+ links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
+ if (outerTypeParameters) {
+ root.instantiations = ts.createMap();
+ root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
+ }
}
return links.resolvedType;
}
@@ -32540,14 +32792,18 @@ var ts;
return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
}
function isInferenceContext(mapper) {
- return !!mapper.signature;
+ return !!mapper.typeParameters;
}
function cloneTypeMapper(mapper) {
return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
+ createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
mapper;
}
function combineTypeMappers(mapper1, mapper2) {
+ if (!mapper1)
+ return mapper2;
+ if (!mapper2)
+ return mapper1;
return function (t) { return instantiateType(mapper1(t), mapper2); };
}
function createReplacementMapper(source, target, baseMapper) {
@@ -32729,22 +32985,35 @@ var ts;
return result;
}
function getConditionalTypeInstantiation(type, mapper) {
- var target = type.target || type;
- var combinedMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper;
+ 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, mapper);
+ var id = getTypeListId(typeArguments);
+ var result = root.instantiations.get(id);
+ if (!result) {
+ var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
+ result = instantiateConditionalType(root, newMapper);
+ root.instantiations.set(id, result);
+ }
+ return result;
+ }
+ return type;
+ }
+ function instantiateConditionalType(root, mapper) {
// 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).
- if (isDistributiveConditionalType(target)) {
- var checkType_1 = target.checkType;
- var instantiatedType = combinedMapper(checkType_1);
- if (checkType_1 !== instantiatedType && instantiatedType.flags & 131072 /* Union */) {
- return mapType(instantiatedType, function (t) { return instantiateConditionalType(target, createReplacementMapper(checkType_1, t, combinedMapper)); });
+ if (root.isDistributive) {
+ var checkType_1 = root.checkType;
+ var instantiatedType = mapper(checkType_1);
+ if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 /* Union */ | 16384 /* Never */)) {
+ return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); });
}
}
- return instantiateConditionalType(target, combinedMapper);
- }
- function instantiateConditionalType(type, mapper) {
- return getConditionalType(instantiateType(type.checkType, mapper), type.extendsType, type.trueType, type.falseType, type.inferTypeParameters, type, mapper, type.aliasSymbol, type.aliasTypeArguments);
+ return getConditionalType(root, mapper);
}
function instantiateType(type, mapper) {
if (type && mapper && mapper !== identityMapper) {
@@ -32785,7 +33054,7 @@ var ts;
return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
}
if (type.flags & 2097152 /* Conditional */) {
- return getConditionalTypeInstantiation(type, mapper);
+ return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (type.flags & 4194304 /* Substitution */) {
return mapper(type.typeParameter);
@@ -33458,11 +33727,11 @@ var ts;
}
}
if (flags & 2097152 /* Conditional */) {
- if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
- if (result &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
- if (isDistributiveConditionalType(source) === isDistributiveConditionalType(target)) {
+ if (source.root.isDistributive === target.root.isDistributive) {
+ if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
+ if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
+ if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
return result;
}
}
@@ -33850,20 +34119,11 @@ var ts;
}
}
else if (source.flags & 2097152 /* Conditional */) {
- if (relation !== definitelyAssignableRelation) {
- var constraint = getConstraintOfDistributiveConditionalType(source);
- if (constraint) {
- if (result = isRelatedTo(constraint, target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
- }
- }
- }
if (target.flags & 2097152 /* Conditional */) {
if (isTypeIdenticalTo(source.checkType, target.checkType) &&
isTypeIdenticalTo(source.extendsType, target.extendsType)) {
- if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
- result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
+ if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
+ result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -33871,9 +34131,21 @@ var ts;
}
}
}
- else if (result = isRelatedTo(getDefaultConstraintOfConditionalType(source), target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
+ else if (relation !== definitelyAssignableRelation) {
+ var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
+ if (distributiveConstraint) {
+ if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ var defaultConstraint = getDefaultConstraintOfConditionalType(source);
+ if (defaultConstraint) {
+ if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
}
}
else {
@@ -34738,8 +35010,18 @@ var ts;
ts.Debug.assert(strictNullChecks);
return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]);
}
+ function getGlobalNonNullableTypeInstantiation(type) {
+ 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, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higherorder behavior
+ }
function getNonNullableType(type) {
- return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type;
+ return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
}
/**
* Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
@@ -34841,6 +35123,10 @@ var ts;
}
var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name);
result.type = undefinedType;
+ var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (associatedKeyType.flags & 32 /* StringLiteral */) {
+ result.nameType = associatedKeyType;
+ }
undefinedProperties.set(name, result);
return result;
}
@@ -35004,9 +35290,10 @@ var ts;
callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
}
}
- function createInferenceContext(signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo);
+ function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
+ var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(typeParameters, createInferenceInfo);
var context = mapper;
+ context.typeParameters = typeParameters;
context.signature = signature;
context.inferences = inferences;
context.flags = flags;
@@ -35125,7 +35412,7 @@ var ts;
var templateType = getTemplateTypeFromMappedType(target);
var inference = createInferenceInfo(typeParameter);
inferTypes([inference], sourceType, templateType);
- return getTypeFromInference(inference) || emptyObjectType;
+ return getTypeFromInference(inference);
}
function getUnmatchedProperty(source, target, requireOptionalProperties) {
var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
@@ -35143,18 +35430,29 @@ var ts;
function getTypeFromInference(inference) {
return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
- undefined;
+ emptyObjectType;
}
function inferTypes(inferences, originalSource, originalTarget, priority) {
if (priority === void 0) { priority = 0; }
var symbolStack;
var visited;
var contravariant = false;
+ var propagationType;
inferFromTypes(originalSource, originalTarget);
function inferFromTypes(source, target) {
if (!couldContainTypeVariables(target)) {
return;
}
+ if (source.flags & 1 /* Any */) {
+ // We are inferring from an 'any' type. We want to infer this type for every type parameter
+ // referenced in the target type, so we record it as the propagation type and infer from the
+ // target to itself. Then, as we find candidates we substitute the propagation type.
+ var savePropagationType = propagationType;
+ propagationType = source;
+ inferFromTypes(target, target);
+ propagationType = savePropagationType;
+ return;
+ }
if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
// Source and target are types originating in the same generic type alias declaration.
// Simply infer from source type arguments to target type arguments.
@@ -35224,14 +35522,15 @@ var ts;
inference.priority = priority;
}
if (priority === inference.priority) {
+ var candidate = propagationType || source;
if (contravariant) {
- inference.contraCandidates = ts.append(inference.contraCandidates, source);
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
}
else {
- inference.candidates = ts.append(inference.candidates, source);
+ inference.candidates = ts.append(inference.candidates, candidate);
}
}
- if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
}
}
@@ -35271,8 +35570,8 @@ var ts;
else if (source.flags & 2097152 /* Conditional */ && target.flags & 2097152 /* Conditional */) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(source.trueType, target.trueType);
- inferFromTypes(source.falseType, target.falseType);
+ inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
+ inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
}
else if (target.flags & 393216 /* UnionOrIntersection */) {
var targetTypes = target.types;
@@ -35308,7 +35607,7 @@ var ts;
}
}
else {
- if (!(priority && 8 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) {
+ if (!(priority & 16 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) {
source = getApparentType(source);
}
if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) {
@@ -35339,7 +35638,7 @@ var ts;
}
}
function inferFromContravariantTypes(source, target) {
- if (strictFunctionTypes || priority & 16 /* AlwaysStrict */) {
+ if (strictFunctionTypes || priority & 32 /* AlwaysStrict */) {
contravariant = !contravariant;
inferFromTypes(source, target);
contravariant = !contravariant;
@@ -35378,7 +35677,7 @@ var ts;
var inferredType = inferTypeForHomomorphicMappedType(source, target);
if (inferredType) {
var savePriority = priority;
- priority |= 2 /* MappedType */;
+ priority |= 2 /* HomomorphicMappedType */;
inferFromTypes(inferredType, inference.typeParameter);
priority = savePriority;
}
@@ -35388,7 +35687,10 @@ var ts;
if (constraintType.flags & 32768 /* TypeParameter */) {
// We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
// parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
+ var savePriority = priority;
+ priority |= 4 /* MappedTypeConstraint */;
inferFromTypes(getIndexType(source), constraintType);
+ priority = savePriority;
inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target));
return;
}
@@ -35497,58 +35799,63 @@ var ts;
var inference = context.inferences[index];
var inferredType = inference.inferredType;
if (!inferredType) {
- if (inference.candidates) {
- // Extract all object literal types and replace them with a single widened and normalized type.
- var candidates = widenObjectLiteralCandidates(inference.candidates);
- // We widen inferred literal types if
- // all inferences were made to top-level ocurrences of the type parameter, and
- // the type parameter has no constraint or its constraint includes no primitive or literal types, and
- // the type parameter was fixed during inference or does not occur at top-level in the return type.
- var signature = context.signature;
- var widenLiteralTypes = inference.topLevel &&
- !hasPrimitiveConstraint(inference.typeParameter) &&
- (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
- var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
- // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if
- // union types were requested or if all inferences were made from the return type position, infer a
- // union type. Otherwise, infer a common supertype.
- var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ?
- getUnionType(baseCandidates, 2 /* Subtype */) :
- getCommonSupertype(baseCandidates);
- inferredType = getWidenedType(unwidenedType);
- // If we have inferred 'never' but have contravariant candidates. To get a more specific type we
- // infer from the contravariant candidates instead.
- if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) {
+ var signature = context.signature;
+ if (signature) {
+ if (inference.candidates) {
+ // Extract all object literal types and replace them with a single widened and normalized type.
+ var candidates = widenObjectLiteralCandidates(inference.candidates);
+ // We widen inferred literal types if
+ // all inferences were made to top-level ocurrences of the type parameter, and
+ // the type parameter has no constraint or its constraint includes no primitive or literal types, and
+ // the type parameter was fixed during inference or does not occur at top-level in the return type.
+ var widenLiteralTypes = inference.topLevel &&
+ !hasPrimitiveConstraint(inference.typeParameter) &&
+ (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
+ var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates;
+ // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if
+ // union types were requested or if all inferences were made from the return type position, infer a
+ // union type. Otherwise, infer a common supertype.
+ var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 12 /* PriorityImpliesUnion */ ?
+ getUnionType(baseCandidates, 2 /* Subtype */) :
+ getCommonSupertype(baseCandidates);
+ inferredType = getWidenedType(unwidenedType);
+ // If we have inferred 'never' but have contravariant candidates. To get a more specific type we
+ // infer from the contravariant candidates instead.
+ if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) {
+ inferredType = getCommonSubtype(inference.contraCandidates);
+ }
+ }
+ else if (inference.contraCandidates) {
+ // We only have contravariant inferences, infer the best common subtype of those
inferredType = getCommonSubtype(inference.contraCandidates);
}
- }
- else if (inference.contraCandidates) {
- // We only have contravariant inferences, infer the best common subtype of those
- inferredType = getCommonSubtype(inference.contraCandidates);
- }
- else if (context.flags & 2 /* NoDefault */) {
- // We use silentNeverType as the wildcard that signals no inferences.
- inferredType = silentNeverType;
- }
- else {
- // Infer either the default or the empty object type when no inferences were
- // made. It is important to remember that in this case, inference still
- // succeeds, meaning there is no error for not having inference candidates. An
- // inference error only occurs when there are *conflicting* candidates, i.e.
- // candidates with no common supertype.
- var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
- if (defaultType) {
- // Instantiate the default type. Any forward reference to a type
- // parameter should be instantiated to the empty object type.
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ else if (context.flags & 2 /* NoDefault */) {
+ // We use silentNeverType as the wildcard that signals no inferences.
+ inferredType = silentNeverType;
}
else {
- inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */));
+ // Infer either the default or the empty object type when no inferences were
+ // made. It is important to remember that in this case, inference still
+ // succeeds, meaning there is no error for not having inference candidates. An
+ // inference error only occurs when there are *conflicting* candidates, i.e.
+ // candidates with no common supertype.
+ var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
+ if (defaultType) {
+ // Instantiate the default type. Any forward reference to a type
+ // parameter should be instantiated to the empty object type.
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ }
+ else {
+ inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */));
+ }
}
}
+ else {
+ inferredType = getTypeFromInference(inference);
+ }
inferredType = getWidenedUniqueESSymbolType(inferredType);
inference.inferredType = inferredType;
- var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]);
+ var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
var instantiatedConstraint = instantiateType(constraint, context);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
@@ -35593,7 +35900,7 @@ var ts;
function getFlowCacheKey(node) {
if (node.kind === 71 /* Identifier */) {
var symbol = getResolvedSymbol(node);
- return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
+ return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
}
if (node.kind === 99 /* ThisKeyword */) {
return "0";
@@ -35812,8 +36119,8 @@ var ts;
}
if (flags & 65536 /* Object */) {
return isFunctionObjectType(type) ?
- strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ :
- strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */;
+ strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ :
+ strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */;
}
if (flags & (2048 /* Void */ | 4096 /* Undefined */)) {
return 2457472 /* UndefinedFacts */;
@@ -35825,7 +36132,7 @@ var ts;
return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */;
}
if (flags & 134217728 /* NonPrimitive */) {
- return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */;
+ return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */;
}
if (flags & 7897088 /* Instantiable */) {
return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType);
@@ -35833,7 +36140,7 @@ var ts;
if (flags & 393216 /* UnionOrIntersection */) {
return getTypeFactsOfTypes(type.types);
}
- return 8388607 /* All */;
+ return 4194303 /* All */;
}
function getTypeWithFacts(type, include) {
return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
@@ -36031,6 +36338,9 @@ var ts;
// is a union type, the mapping function is applied to each constituent type and a union
// of the resulting types is returned.
function mapType(type, mapper, noReductions) {
+ if (type.flags & 16384 /* Never */) {
+ return type;
+ }
if (!(type.flags & 131072 /* Union */)) {
return mapper(type);
}
@@ -36869,24 +37179,23 @@ var ts;
!(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */);
return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType;
}
- function isApparentTypePosition(node) {
+ function isConstraintPosition(node) {
var parent = node.parent;
return parent.kind === 183 /* PropertyAccessExpression */ ||
parent.kind === 185 /* CallExpression */ && parent.expression === node ||
parent.kind === 184 /* ElementAccessExpression */ && parent.expression === node ||
- parent.kind === 207 /* NonNullExpression */ ||
parent.kind === 180 /* BindingElement */ && parent.name === node && !!parent.initializer;
}
function typeHasNullableConstraint(type) {
return type.flags & 7372800 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */);
}
- function getApparentTypeForLocation(type, node) {
+ 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 (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) {
- return mapType(getWidenedType(type), getApparentType);
+ if (isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
+ return mapType(getWidenedType(type), getBaseConstraintOrType);
}
return type;
}
@@ -36963,7 +37272,7 @@ var ts;
checkCollisionWithCapturedThisVariable(node, node);
checkCollisionWithCapturedNewTargetVariable(node, node);
checkNestedBlockScopedBinding(node, symbol);
- var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node);
+ var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
var assignmentKind = ts.getAssignmentTargetKind(node);
if (assignmentKind) {
if (!(localOrExportSymbol.flags & 3 /* Variable */)) {
@@ -37613,7 +37922,7 @@ var ts;
var func = ts.getContainingFunction(node);
if (func) {
var functionFlags = ts.getFunctionFlags(func);
- if (functionFlags & 1 /* Generator */) {
+ if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
return undefined;
}
var contextualReturnType = getContextualReturnType(func);
@@ -37781,7 +38090,7 @@ var ts;
function getContextualTypeForChildJsxExpression(node) {
var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
// JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined;
}
function getContextualTypeForJsxExpression(node) {
@@ -37933,15 +38242,9 @@ var ts;
return anyType;
}
var isJs = ts.isInJavaScriptFile(node);
- return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes);
+ return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); });
}
- function getJsxSignaturesParameterTypes(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ false);
- }
- function getJsxSignaturesParameterTypesJs(valueType) {
- return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ true);
- }
- function getJsxSignaturesParameterTypesInternal(valueType, isJs) {
+ function getJsxSignaturesParameterTypes(valueType, isJs, context) {
// If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type
if (valueType.flags & 2 /* String */) {
return anyType;
@@ -37951,7 +38254,7 @@ var ts;
// For example:
// var CustomTag: "h1" = "h1";
// Hello World
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = valueType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -37977,21 +38280,21 @@ var ts;
return unknownType;
}
}
- return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0 /* None */);
+ return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */);
}
- function getJsxPropsTypeFromCallSignature(sig) {
+ function getJsxPropsTypeFromCallSignature(sig, context) {
var propsType = getTypeOfFirstParameterOfSignature(sig);
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
propsType = intersectTypes(intrinsicAttribs, propsType);
}
return propsType;
}
- function getJsxPropsTypeFromClassType(hostClassType, isJs) {
+ function getJsxPropsTypeFromClassType(hostClassType, isJs, context) {
if (isTypeAny(hostClassType)) {
return hostClassType;
}
- var propsName = getJsxElementPropertiesName();
+ var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context));
if (propsName === undefined) {
// There is no type ElementAttributesProperty, return 'any'
return anyType;
@@ -38013,14 +38316,14 @@ var ts;
else {
// Normal case -- add in IntrinsicClassElements and IntrinsicElements
var apparentAttributesType = attributesType;
- var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes);
+ var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
if (intrinsicClassAttribs !== unknownType) {
var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
apparentAttributesType = intersectTypes(typeParams
? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs))
: intrinsicClassAttribs, apparentAttributesType);
}
- var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
if (intrinsicAttribs !== unknownType) {
apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
}
@@ -38028,18 +38331,12 @@ var ts;
}
}
}
- function getJsxPropsTypeFromConstructSignatureJs(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ true);
- }
- function getJsxPropsTypeFromConstructSignature(sig) {
- return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ false);
- }
- function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) {
+ function getJsxPropsTypeFromConstructSignature(sig, isJs, context) {
var hostClassType = getReturnTypeOfSignature(sig);
if (hostClassType) {
- return getJsxPropsTypeFromClassType(hostClassType, isJs);
+ return getJsxPropsTypeFromClassType(hostClassType, isJs, context);
}
- return getJsxPropsTypeFromCallSignature(sig);
+ return getJsxPropsTypeFromCallSignature(sig, context);
}
// 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.
@@ -38329,9 +38626,13 @@ var ts;
}
typeFlags |= type.flags;
var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined;
- var prop = nameType && isTypeUsableAsLateBoundName(nameType)
+ var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType);
+ var prop = hasLateBoundName
? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */)
: createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName);
+ if (hasLateBoundName) {
+ prop.nameType = nameType;
+ }
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.
@@ -38455,7 +38756,7 @@ var ts;
}
function checkJsxSelfClosingElement(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode);
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxElement(node, checkMode) {
// Check attributes
@@ -38467,14 +38768,16 @@ var ts;
else {
checkExpression(node.closingElement.tagName);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
function checkJsxFragment(node, checkMode) {
checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode);
- if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) {
- error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory);
+ if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
+ error(node, compilerOptions.jsxFactory
+ ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
+ : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
}
- return getJsxGlobalElementType() || anyType;
+ return getJsxElementTypeAt(node) || anyType;
}
/**
* Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
@@ -38519,7 +38822,7 @@ var ts;
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var jsxChildrenPropertyName = getJsxElementChildrenPropertyName();
+ var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
var attributeDecl = _a[_i];
var member = attributeDecl.symbol;
@@ -38624,12 +38927,11 @@ var ts;
function checkJsxAttributes(node, checkMode) {
return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
}
- function getJsxType(name) {
- var jsxType = jsxTypes.get(name);
- if (jsxType === undefined) {
- jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType);
- }
- return jsxType;
+ function getJsxType(name, location) {
+ var namespace = getJsxNamespaceAt(location);
+ var exports = namespace && getExportsOfSymbol(namespace);
+ var typeSymbol = exports && getSymbol(exports, name, 793064 /* Type */);
+ return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType;
}
/**
* Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
@@ -38640,11 +38942,11 @@ var ts;
function getIntrinsicTagSymbol(node) {
var links = getNodeLinks(node);
if (!links.resolvedSymbol) {
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
if (intrinsicElementsType !== unknownType) {
// Property case
if (!ts.isIdentifier(node.tagName))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
if (intrinsicProp) {
links.jsxFlags |= 1 /* IntrinsicNamedElement */;
@@ -38697,7 +38999,7 @@ var ts;
var signature = signatures_3[_i];
if (signature.typeParameters) {
var isJavascript = ts.isInJavaScriptFile(node);
- var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */);
+ var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */);
var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext);
instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript));
}
@@ -38707,6 +39009,18 @@ var ts;
}
return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */);
}
+ function getJsxNamespaceAt(location) {
+ var namespaceName = getJsxNamespace(location);
+ var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
+ if (resolvedNamespace) {
+ var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */);
+ if (candidate) {
+ return candidate;
+ }
+ }
+ // JSX global fallback
+ return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined);
+ }
/**
* Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
* Get a single property from that container if existed. Report an error if there are more than one property.
@@ -38714,9 +39028,7 @@ var ts;
* @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
* if other string is given or the container doesn't exist, return undefined.
*/
- function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) {
- // JSX
- var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined);
+ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
// JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */);
// JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
@@ -38728,6 +39040,8 @@ var ts;
if (propertiesOfJsxElementAttribPropInterface.length === 0) {
return "";
}
+ // Element Attributes has one property, so the element attributes type will be the type of the corresponding
+ // property of the class instance type
else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
return propertiesOfJsxElementAttribPropInterface[0].escapedName;
}
@@ -38743,19 +39057,11 @@ var ts;
/// non-intrinsic elements' attributes type is 'any'),
/// or '' if it has 0 properties (which means every
/// non-intrinsic elements' attributes type is the element instance type)
- function getJsxElementPropertiesName() {
- if (!_hasComputedJsxElementPropertiesName) {
- _hasComputedJsxElementPropertiesName = true;
- _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer);
- }
- return _jsxElementPropertiesName;
+ function getJsxElementPropertiesName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
}
- function getJsxElementChildrenPropertyName() {
- if (!_hasComputedJsxElementChildrenPropertyName) {
- _hasComputedJsxElementChildrenPropertyName = true;
- _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer);
- }
- return _jsxElementChildrenPropertyName;
+ function getJsxElementChildrenPropertyName(jsxNamespace) {
+ return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
}
function getApparentTypeOfJsxPropsType(propsType) {
if (!propsType) {
@@ -38784,7 +39090,7 @@ var ts;
function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
ts.Debug.assert(!(elementType.flags & 131072 /* Union */));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
// We don't call getResolvedSignature here because we have already resolve the type of JSX Element.
var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined);
@@ -38794,7 +39100,7 @@ var ts;
paramType = getApparentTypeOfJsxPropsType(paramType);
if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
// Intersect in JSX.IntrinsicAttributes if it exists
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
paramType = intersectTypes(intrinsicAttributes, paramType);
}
@@ -38819,7 +39125,7 @@ var ts;
ts.Debug.assert(!(elementType.flags & 131072 /* Union */));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
// Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type
- var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
if (jsxStatelessElementType) {
// We don't call getResolvedSignature because here we have already resolve the type of JSX Element.
var candidatesOutArray = [];
@@ -38853,7 +39159,7 @@ var ts;
result = allMatchingAttributesType;
}
// Intersect in JSX.IntrinsicAttributes if it exists
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
if (intrinsicAttributes !== unknownType) {
result = intersectTypes(intrinsicAttributes, result);
}
@@ -38896,7 +39202,7 @@ var ts;
// For example:
// var CustomTag: "h1" = "h1";
// Hello World
- var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
+ var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement);
if (intrinsicElementsType !== unknownType) {
var stringLiteralTypeName = elementType.value;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
@@ -38926,7 +39232,7 @@ var ts;
if (elementClassType) {
checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
}
- return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement));
+ return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement);
}
/**
* Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
@@ -38957,7 +39263,7 @@ var ts;
* @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component
*/
function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) {
- return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType());
+ return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node));
}
/**
* Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element.
@@ -38997,32 +39303,26 @@ var ts;
var prop = getPropertyOfType(attributesType, attrib.name.escapedText);
return prop || unknownSymbol;
}
- function getJsxGlobalElementClassType() {
- if (!deferredJsxElementClassType) {
- deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass);
- }
- return deferredJsxElementClassType;
+ function getJsxElementClassTypeAt(location) {
+ var type = getJsxType(JsxNames.ElementClass, location);
+ if (type === unknownType)
+ return undefined;
+ return type;
}
- function getJsxGlobalElementType() {
- if (!deferredJsxElementType) {
- deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element);
- }
- return deferredJsxElementType;
+ function getJsxElementTypeAt(location) {
+ return getJsxType(JsxNames.Element, location);
}
- function getJsxGlobalStatelessElementType() {
- if (!deferredJsxStatelessElementType) {
- var jsxElementType = getJsxGlobalElementType();
- if (jsxElementType) {
- deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]);
- }
+ function getJsxStatelessElementTypeAt(location) {
+ var jsxElementType = getJsxElementTypeAt(location);
+ if (jsxElementType) {
+ return getUnionType([jsxElementType, nullType]);
}
- return deferredJsxStatelessElementType;
}
/**
* Returns all the properties of the Jsx.IntrinsicElements interface
*/
- function getJsxIntrinsicTagNames() {
- var intrinsics = getJsxType(JsxNames.IntrinsicElements);
+ function getJsxIntrinsicTagNamesAt(location) {
+ var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
}
function checkJsxPreconditions(errorNode) {
@@ -39030,7 +39330,7 @@ var ts;
if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
}
- if (getJsxGlobalElementType() === undefined) {
+ if (getJsxElementTypeAt(errorNode) === undefined) {
if (noImplicitAny) {
error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
}
@@ -39045,7 +39345,7 @@ var ts;
// The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
// And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
- var reactNamespace = getJsxNamespace();
+ var reactNamespace = getJsxNamespace(node);
var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
var reactSym = resolveName(reactLocation, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
if (reactSym) {
@@ -39121,7 +39421,7 @@ var ts;
// If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type.
// but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass.
if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || getPropertiesOfType(sourceAttributesType).length > 0)) {
- error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName()));
+ error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement))));
}
else {
// Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties
@@ -39328,7 +39628,7 @@ var ts;
return unknownType;
}
}
- propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node);
+ propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
}
// 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,
@@ -39454,6 +39754,10 @@ var ts;
});
return result && ts.symbolName(result);
}
+ function getSuggestionForNonexistentModule(name, targetModule) {
+ var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
+ return suggestion && ts.symbolName(suggestion);
+ }
/**
* Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
* Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
@@ -39866,13 +40170,13 @@ var ts;
}
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
- var context = createInferenceContext(signature, 1 /* InferUnionTypes */, compareTypes);
+ var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes);
forEachMatchingParameterType(contextualSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target);
});
if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */);
+ inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration));
}
@@ -39923,7 +40227,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, 4 /* ReturnType */);
+ inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -40556,7 +40860,7 @@ var ts;
}
var candidate = void 0;
var inferenceContext = originalCandidate.typeParameters ?
- createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) :
+ createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) :
undefined;
while (true) {
candidate = originalCandidate;
@@ -41128,7 +41432,7 @@ var ts;
}
// Make sure require is not a local function
if (!ts.isIdentifier(node.expression))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
if (!resolvedRequire) {
// project does not contain symbol named 'require' - assume commonjs require
@@ -41320,7 +41624,7 @@ var ts;
}
else {
var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
- if (functionFlags & 1 /* Generator */) {
+ if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types);
if (!types || types.length === 0) {
var iterableIteratorAny = functionFlags & 2 /* Async */
@@ -41586,7 +41890,7 @@ var ts;
((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ?
checkAsyncFunctionReturnType(node) : // Async function
getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function
- if ((functionFlags & 1 /* Generator */) === 0) {
+ if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
// return is not necessary in the body of generators
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
}
@@ -41610,11 +41914,11 @@ var ts;
// its return type annotation.
var exprType = checkExpression(node.body);
if (returnOrPromisedType) {
- if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) {
+ if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body);
}
- else {
+ else { // Normal function
checkTypeAssignableTo(exprType, returnOrPromisedType, node.body);
}
}
@@ -42771,6 +43075,7 @@ var ts;
if (node.kind === 159 /* 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 === 162 /* FunctionType */ || node.kind === 232 /* FunctionDeclaration */ || node.kind === 163 /* ConstructorType */ ||
node.kind === 157 /* CallSignature */ || node.kind === 154 /* Constructor */ ||
node.kind === 158 /* ConstructSignature */) {
@@ -43589,7 +43894,7 @@ var ts;
case 230 /* VariableDeclaration */:
case 180 /* BindingElement */:
case 232 /* FunctionDeclaration */:
- case 246 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591
+ case 246 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
return 1 /* ExportValue */;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(d));
@@ -44113,7 +44418,7 @@ var ts;
var body = node.kind === 152 /* MethodSignature */ ? undefined : node.body;
checkSourceElement(body);
var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
- if ((functionFlags & 1 /* Generator */) === 0) {
+ if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */
? checkAsyncFunctionReturnType(node) // Async function
: getTypeFromTypeNode(returnTypeNode)); // normal function
@@ -44488,7 +44793,7 @@ var ts;
var symbol = getSymbolOfNode(node);
if (symbol.flags & 1 /* FunctionScopedVariable */) {
if (!ts.isIdentifier(node.name))
- throw ts.Debug.fail();
+ return ts.Debug.fail();
var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
if (localDeclarationSymbol &&
localDeclarationSymbol !== symbol &&
@@ -45191,7 +45496,7 @@ var ts;
var isGenerator = functionFlags & 1 /* Generator */;
if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) {
var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
- if (isGenerator) {
+ if (isGenerator) { // AsyncGenerator function or Generator function
// A generator does not need its return expressions checked against its return type.
// Instead, the yield expressions are checked against the element type.
// TODO: Check return types of generators when return type tracking is added
@@ -45209,7 +45514,7 @@ var ts;
}
}
else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) {
- if (functionFlags & 2 /* Async */) {
+ if (functionFlags & 2 /* Async */) { // Async function
var promisedType = getPromisedTypeOfPromise(returnType);
var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
if (promisedType) {
@@ -45651,7 +45956,7 @@ var ts;
var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
if (prop && baseProp) {
var rootChain = function () { return ts.chainDiagnosticMessages(
- /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); };
+ /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); };
if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
issuedMemberError = true;
}
@@ -46166,7 +46471,6 @@ var ts;
// - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
if (checkBody && node.body) {
- // body of ambient external module is always a module block
for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
var statement = _a[_i];
checkModuleAugmentationElement(statement, isGlobalAugmentation);
@@ -46271,7 +46575,11 @@ var ts;
}
function checkExternalImportOrExportDeclaration(node) {
var moduleName = ts.getExternalModuleName(node);
- if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) {
+ if (ts.nodeIsMissing(moduleName)) {
+ // Should be a parse error.
+ return false;
+ }
+ if (!ts.isStringLiteral(moduleName)) {
error(moduleName, ts.Diagnostics.String_literal_expected);
return false;
}
@@ -46282,7 +46590,7 @@ var ts;
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
return false;
}
- if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) {
+ if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
// we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration
// no need to do this again.
if (!isTopLevelInExternalModuleAugmentation(node)) {
@@ -47870,7 +48178,7 @@ var ts;
return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */);
},
writeLiteralConstValue: writeLiteralConstValue,
- getJsxFactoryEntity: function () { return _jsxFactoryEntity; }
+ getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }
};
// defined here to avoid outer scope pollution
function getTypeReferenceDirectivesForEntityName(node) {
@@ -49283,7 +49591,7 @@ var ts;
case 243 /* ImportClause */: // For default import
case 241 /* ImportEqualsDeclaration */:
case 244 /* NamespaceImport */:
- case 246 /* ImportSpecifier */:// For rename import `x as y`
+ case 246 /* ImportSpecifier */: // For rename import `x as y`
return true;
case 71 /* Identifier */:
// For regular import, `decl` is an Identifier under the ImportSpecifier.
@@ -49501,9 +49809,15 @@ var ts;
: node;
}
ts.updateQualifiedName = updateQualifiedName;
+ function parenthesizeForComputedName(expression) {
+ return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) ||
+ expression.kind === 296 /* CommaListExpression */ ?
+ createParen(expression) :
+ expression;
+ }
function createComputedPropertyName(expression) {
var node = createSynthesizedNode(146 /* ComputedPropertyName */);
- node.expression = expression;
+ node.expression = parenthesizeForComputedName(expression);
return node;
}
ts.createComputedPropertyName = createComputedPropertyName;
@@ -51300,7 +51614,7 @@ var ts;
var node = createSynthesizedNode(268 /* PropertyAssignment */);
node.name = asName(name);
node.questionToken = undefined;
- node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
+ node.initializer = ts.parenthesizeExpressionForList(initializer);
return node;
}
ts.createPropertyAssignment = createPropertyAssignment;
@@ -51410,6 +51724,12 @@ var ts;
updated.imports = node.imports;
if (node.moduleAugmentations !== undefined)
updated.moduleAugmentations = node.moduleAugmentations;
+ if (node.pragmas !== undefined)
+ updated.pragmas = node.pragmas;
+ if (node.localJsxFactory !== undefined)
+ updated.localJsxFactory = node.localJsxFactory;
+ if (node.localJsxNamespace !== undefined)
+ updated.localJsxNamespace = node.localJsxNamespace;
return updateNode(updated, node);
}
return node;
@@ -54339,7 +54659,7 @@ var ts;
var isDebugInfoEnabled = false;
Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */)
? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); }
- : ts.noop;
+ : ts.noop; // TODO: GH#22091
Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */)
? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); }
: ts.noop;
@@ -54444,7 +54764,7 @@ var ts;
var uniqueExports = ts.createMap();
var exportedNames;
var hasExportDefault = false;
- var exportEquals = undefined;
+ var exportEquals;
var hasExportStarsToExportValues = false;
var hasImportStarOrImportDefault = false;
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
@@ -56048,7 +56368,7 @@ var ts;
ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
var localName = ts.getMutableClone(name);
ts.setEmitFlags(localName, 1536 /* NoComments */);
- return ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)));
+ return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */));
}
/**
* Gets all property declarations with initializers on either the static or instance side of a class.
@@ -56711,6 +57031,8 @@ var ts;
// One of the individual is global object, return immediately
return serializedIndividual;
}
+ // If there exists union that is not void 0 expression, check if the the common type is identifier.
+ // anything more complex and we will just default to Object
else if (serializedUnion) {
// Different types
if (!ts.isIdentifier(serializedUnion) ||
@@ -56874,7 +57196,7 @@ var ts;
function visitPropertyNameOfClassElement(member) {
var name = member.name;
var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false);
- if (expr) {
+ if (expr) { // expr only exists if `name` is a computed property name
// Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order
if (ts.some(pendingExpressions)) {
expr = ts.inlineExpressions(pendingExpressions.concat([expr]));
@@ -59225,14 +59547,14 @@ var ts;
objectProperties = ts.createAssignHelper(context, segments);
}
}
- var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
return element;
}
function visitJsxOpeningFragment(node, children, isChild, location) {
- var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
+ var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location);
if (isChild) {
ts.startOnNewLine(element);
}
@@ -60424,6 +60746,7 @@ var ts;
if (statement.kind === 223 /* ReturnStatement */) {
return true;
}
+ // An if-statement with two covered branches is covered.
else if (statement.kind === 215 /* IfStatement */) {
var ifStatement = statement;
if (ifStatement.elseStatement) {
@@ -60431,6 +60754,7 @@ var ts;
isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
}
}
+ // A block is covered if it has a last statement which is covered.
else if (statement.kind === 211 /* Block */) {
var lastStatement = ts.lastOrUndefined(statement.statements);
if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
@@ -60629,11 +60953,11 @@ var ts;
function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
initializer = ts.visitNode(initializer, visitor, ts.isExpression);
var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
- ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter))
- ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */));
+ ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
+ ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
- ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */);
+ ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
statements.push(statement);
}
/**
@@ -65222,6 +65546,7 @@ var ts;
withBlockStack.pop();
}
break;
+ // default: do nothing
}
}
}
@@ -66756,13 +67081,13 @@ var ts;
var importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
- text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}"
+ text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
var importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
- text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}"
+ text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
};
})(ts || (ts = {}));
///
@@ -68740,7 +69065,7 @@ var ts;
}
if (compilerOptions.mapRoot) {
sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot);
- if (sourceFileOrBundle.kind === 272 /* SourceFile */) {
+ if (sourceFileOrBundle.kind === 272 /* SourceFile */) { // emitting single module file
// For modules or multiple emit files the mapRoot will have directory structure like the sources
// So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir));
@@ -69609,8 +69934,8 @@ var ts;
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = ts.createMap();
}
- for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) {
- var directive = typeReferenceDirectives_1[_i];
+ for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
+ var directive = typeReferenceDirectives_2[_i];
if (!usedTypeDirectiveReferences.has(directive)) {
usedTypeDirectiveReferences.set(directive, directive);
}
@@ -69899,7 +70224,12 @@ var ts;
"?");
}
write(": ");
- emitType(node.type);
+ if (node.type) {
+ emitType(node.type);
+ }
+ else {
+ write("any");
+ }
write(";");
writeLine();
decreaseIndent();
@@ -69990,6 +70320,7 @@ var ts;
if (isModuleElementVisible) {
writeModuleElement(node);
}
+ // Import equals declaration in internal module can become visible as part of any emit so lets make sure we add these irrespective
else if (node.kind === 241 /* ImportEqualsDeclaration */ ||
(node.parent.kind === 272 /* SourceFile */ && isCurrentFileExternalModule)) {
var isVisible = void 0;
@@ -70543,6 +70874,8 @@ var ts;
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;
}
+ // 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 === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ ||
(node.kind === 148 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
@@ -71885,6 +72218,8 @@ var ts;
// Enum
case 271 /* EnumMember */:
return emitEnumMember(node);
+ // JSDoc nodes (ignored)
+ // Transformation nodes (ignored)
}
// If the node is an expression, try to emit it as an expression with
// substitution.
@@ -72080,7 +72415,8 @@ var ts;
else {
emitTypeAnnotation(node.type);
}
- emitInitializer(node.initializer);
+ // 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);
}
function emitDecorator(decorator) {
writePunctuation("@");
@@ -72102,8 +72438,9 @@ var ts;
emitModifiers(node, node.modifiers);
emit(node.name);
emitIfPresent(node.questionToken);
+ emitIfPresent(node.exclamationToken);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
writeSemicolon();
}
function emitMethodSignature(node) {
@@ -72348,7 +72685,7 @@ var ts;
writeSpace();
}
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
//
// Expressions
@@ -72385,7 +72722,10 @@ var ts;
emitExpression(node.expression);
increaseIndentIf(indentBeforeDot);
var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression);
- writePunctuation(shouldEmitDotDot ? ".." : ".");
+ if (shouldEmitDotDot) {
+ writePunctuation(".");
+ }
+ emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node);
increaseIndentIf(indentAfterDot);
emit(node.name);
decreaseIndentIf(indentBeforeDot, indentAfterDot);
@@ -72411,9 +72751,9 @@ var ts;
}
function emitElementAccessExpression(node) {
emitExpression(node.expression);
- writePunctuation("[");
+ var openPos = emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
emitExpression(node.argumentExpression);
- writePunctuation("]");
+ emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node);
}
function emitCallExpression(node) {
emitExpression(node.expression);
@@ -72421,7 +72761,7 @@ var ts;
emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */);
}
function emitNewExpression(node) {
- writeKeyword("new");
+ emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
emitTypeArguments(node, node.typeArguments);
@@ -72439,9 +72779,9 @@ var ts;
emitExpression(node.expression);
}
function emitParenthesizedExpression(node) {
- writePunctuation("(");
+ var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
}
function emitFunctionExpression(node) {
emitFunctionDeclarationOrExpression(node);
@@ -72459,22 +72799,22 @@ var ts;
emit(node.equalsGreaterThanToken);
}
function emitDeleteExpression(node) {
- writeKeyword("delete");
+ emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitTypeOfExpression(node) {
- writeKeyword("typeof");
+ emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitVoidExpression(node) {
- writeKeyword("void");
+ emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
function emitAwaitExpression(node) {
- writeKeyword("await");
+ emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
}
@@ -72542,7 +72882,7 @@ var ts;
emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */);
}
function emitYieldExpression(node) {
- writeKeyword("yield");
+ emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node);
emit(node.asteriskToken);
emitExpressionWithLeadingSpace(node.expression);
}
@@ -72586,17 +72926,13 @@ var ts;
// Statements
//
function emitBlock(node) {
- writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
- // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted
- increaseIndent();
- emitLeadingCommentsOfPosition(node.statements.end);
- decreaseIndent();
- writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node);
}
function emitBlockStatements(node, forceSingleLine) {
+ emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */;
emitList(node, node.statements, format);
+ emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
}
function emitVariableStatement(node) {
emitModifiers(node, node.modifiers);
@@ -72611,15 +72947,15 @@ var ts;
writeSemicolon();
}
function emitIfStatement(node) {
- var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node);
+ var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.thenStatement);
if (node.elseStatement) {
writeLineOrSpace(node);
- writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
+ emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
if (node.elseStatement.kind === 215 /* IfStatement */) {
writeSpace();
emit(node.elseStatement);
@@ -72629,8 +72965,15 @@ var ts;
}
}
}
+ function emitWhileClause(node, startPos) {
+ var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node);
+ writeSpace();
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
+ emitExpression(node.expression);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
+ }
function emitDoStatement(node) {
- writeKeyword("do");
+ emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node);
emitEmbeddedStatement(node, node.statement);
if (ts.isBlock(node.statement)) {
writeSpace();
@@ -72638,55 +72981,48 @@ var ts;
else {
writeLineOrSpace(node);
}
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(");");
+ emitWhileClause(node, node.statement.end);
+ writePunctuation(";");
}
function emitWhileStatement(node) {
- writeKeyword("while");
- writeSpace();
- writePunctuation("(");
- emitExpression(node.expression);
- writePunctuation(")");
+ emitWhileClause(node, node.pos);
emitEmbeddedStatement(node, node.statement);
}
function emitForStatement(node) {
- var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
+ var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
emitForBinding(node.initializer);
- writeSemicolon();
+ pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.condition);
- writeSemicolon();
+ pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node);
emitExpressionWithLeadingSpace(node.incrementor);
- writePunctuation(")");
+ emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForInStatement(node) {
- var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("in");
+ emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForOfStatement(node) {
- var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitWithTrailingSpace(node.awaitModifier);
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitForBinding(node.initializer);
writeSpace();
- writeKeyword("of");
+ emitTokenWithComment(144 /* OfKeyword */, node.initializer.end, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitForBinding(node) {
@@ -72700,22 +73036,34 @@ var ts;
}
}
function emitContinueStatement(node) {
- writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword);
+ emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
function emitBreakStatement(node) {
- writeToken(72 /* BreakKeyword */, node.pos, writeKeyword);
+ emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node);
emitWithLeadingSpace(node.label);
writeSemicolon();
}
- function emitTokenWithComment(token, pos, writer, contextNode) {
+ function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
var node = contextNode && ts.getParseTreeNode(contextNode);
- if (node && node.kind === contextNode.kind) {
+ var isSimilarNode = node && node.kind === contextNode.kind;
+ var startPos = pos;
+ if (isSimilarNode) {
pos = ts.skipTrivia(currentSourceFile.text, pos);
}
- pos = writeToken(token, pos, writer, /*contextNode*/ contextNode);
- if (node && node.kind === contextNode.kind) {
+ if (emitLeadingCommentsOfPosition && isSimilarNode) {
+ var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
+ if (needsIndent) {
+ increaseIndent();
+ }
+ emitLeadingCommentsOfPosition(startPos);
+ if (needsIndent) {
+ decreaseIndent();
+ }
+ }
+ pos = writeTokenText(token, writer, pos);
+ if (emitTrailingCommentsOfPosition && isSimilarNode) {
emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
}
return pos;
@@ -72726,35 +73074,35 @@ var ts;
writeSemicolon();
}
function emitWithStatement(node) {
- writeKeyword("with");
+ var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writePunctuation("(");
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writePunctuation(")");
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
emitEmbeddedStatement(node, node.statement);
}
function emitSwitchStatement(node) {
- var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emitExpression(node.expression);
- writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
writeSpace();
emit(node.caseBlock);
}
function emitLabeledStatement(node) {
emit(node.label);
- writePunctuation(":");
+ emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node);
writeSpace();
emit(node.statement);
}
function emitThrowStatement(node) {
- writeKeyword("throw");
+ emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node);
emitExpressionWithLeadingSpace(node.expression);
writeSemicolon();
}
function emitTryStatement(node) {
- writeKeyword("try");
+ emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node);
writeSpace();
emit(node.tryBlock);
if (node.catchClause) {
@@ -72763,7 +73111,7 @@ var ts;
}
if (node.finallyBlock) {
writeLineOrSpace(node);
- writeKeyword("finally");
+ emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
writeSpace();
emit(node.finallyBlock);
}
@@ -72778,7 +73126,7 @@ var ts;
function emitVariableDeclaration(node) {
emit(node.name);
emitTypeAnnotation(node.type);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
}
function emitVariableDeclarationList(node) {
writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var");
@@ -72979,23 +73327,21 @@ var ts;
}
function emitModuleBlock(node) {
pushNameGenerationScope(node);
- writePunctuation("{");
emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
- writePunctuation("}");
popNameGenerationScope(node);
}
function emitCaseBlock(node) {
- writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation);
+ emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node);
emitList(node, node.clauses, 65 /* CaseBlockClauses */);
- writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation);
+ emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
}
function emitImportEqualsDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSpace();
- writePunctuation("=");
+ emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node);
writeSpace();
emitModuleReference(node.moduleReference);
writeSemicolon();
@@ -73010,12 +73356,12 @@ var ts;
}
function emitImportDeclaration(node) {
emitModifiers(node, node.modifiers);
- writeKeyword("import");
+ emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
writeSpace();
if (node.importClause) {
emit(node.importClause);
writeSpace();
- writeKeyword("from");
+ emitTokenWithComment(142 /* FromKeyword */, node.importClause.end, writeKeyword, node);
writeSpace();
}
emitExpression(node.moduleSpecifier);
@@ -73024,15 +73370,15 @@ var ts;
function emitImportClause(node) {
emit(node.name);
if (node.name && node.namedBindings) {
- writePunctuation(",");
+ emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node);
writeSpace();
}
emit(node.namedBindings);
}
function emitNamespaceImport(node) {
- writePunctuation("*");
+ var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node);
writeSpace();
emit(node.name);
}
@@ -73043,41 +73389,42 @@ var ts;
emitImportOrExportSpecifier(node);
}
function emitExportAssignment(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
writeSpace();
if (node.isExportEquals) {
- writeOperator("=");
+ emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node);
}
else {
- writeKeyword("default");
+ emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node);
}
writeSpace();
emitExpression(node.expression);
writeSemicolon();
}
function emitExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
writeSpace();
if (node.exportClause) {
emit(node.exportClause);
}
else {
- writePunctuation("*");
+ nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node);
}
if (node.moduleSpecifier) {
writeSpace();
- writeKeyword("from");
+ var fromPos = node.exportClause ? node.exportClause.end : nextPos;
+ emitTokenWithComment(142 /* FromKeyword */, fromPos, writeKeyword, node);
writeSpace();
emitExpression(node.moduleSpecifier);
}
writeSemicolon();
}
function emitNamespaceExportDeclaration(node) {
- writeKeyword("export");
+ var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
writeSpace();
- writeKeyword("as");
+ nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node);
writeSpace();
- writeKeyword("namespace");
+ nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node);
writeSpace();
emit(node.name);
writeSemicolon();
@@ -73097,7 +73444,7 @@ var ts;
if (node.propertyName) {
emit(node.propertyName);
writeSpace();
- writeKeyword("as");
+ emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
writeSpace();
}
emit(node.name);
@@ -73189,44 +73536,31 @@ var ts;
// Clauses
//
function emitCaseClause(node) {
- writeKeyword("case");
+ emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node);
writeSpace();
emitExpression(node.expression);
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
}
function emitDefaultClause(node) {
- writeKeyword("default");
- writePunctuation(":");
- emitCaseOrDefaultClauseStatements(node, node.statements);
+ var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node);
+ emitCaseOrDefaultClauseRest(node, node.statements, pos);
}
- function emitCaseOrDefaultClauseStatements(parentNode, statements) {
+ function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
var emitAsSingleStatement = statements.length === 1 &&
(
// treat synthesized nodes as located on the same line for emit purposes
ts.nodeIsSynthesized(parentNode) ||
ts.nodeIsSynthesized(statements[0]) ||
ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
- // e.g:
- // case 0: // Zero
- // case 1: // One
- // case 2: // two
- // return "hi";
- // If there is no statements, emitNodeWithComments of the parentNode which is caseClause will take care of trailing comment.
- // So in example above, comment "// Zero" and "// One" will be emit in emitTrailingComments in emitNodeWithComments.
- // However, for "case 2", because parentNode which is caseClause has an "end" property to be end of the statements (in this case return statement)
- // comment "// two" will not be emitted in emitNodeWithComments.
- // Therefore, we have to do the check here to emit such comment.
- if (statements.length > 0) {
- // We use emitTrailingCommentsOfPosition instead of emitLeadingCommentsOfPosition because leading comments is defined as comments before the node after newline character separating it from previous line
- // Note: we can't use parentNode.end as such position includes statements.
- emitTrailingCommentsOfPosition(statements.pos);
- }
var format = 81985 /* CaseOrDefaultClauseStatements */;
if (emitAsSingleStatement) {
+ writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode);
writeSpace();
format &= ~(1 /* MultiLine */ | 64 /* Indented */);
}
+ else {
+ emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode);
+ }
emitList(parentNode, statements, format);
}
function emitHeritageClause(node) {
@@ -73236,12 +73570,12 @@ var ts;
emitList(node, node.types, 272 /* HeritageClauseTypes */);
}
function emitCatchClause(node) {
- var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword);
+ var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node);
writeSpace();
if (node.variableDeclaration) {
- writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation);
+ emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
emit(node.variableDeclaration);
- writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation);
+ emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
writeSpace();
}
emit(node.block);
@@ -73287,7 +73621,7 @@ var ts;
//
function emitEnumMember(node) {
emit(node.name);
- emitInitializer(node.initializer);
+ emitInitializer(node.initializer, node.name.end, node);
}
//
// Top-level nodes
@@ -73404,10 +73738,10 @@ var ts;
emit(node);
}
}
- function emitInitializer(node) {
+ function emitInitializer(node, equalCommentStartPos, container) {
if (node) {
writeSpace();
- writeOperator("=");
+ emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
writeSpace();
emitExpression(node);
}
@@ -73455,7 +73789,7 @@ var ts;
emitList(parentNode, typeArguments, 26896 /* TypeArguments */);
}
function emitTypeParameters(parentNode, typeParameters) {
- if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) {
+ if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
return emitTypeArguments(parentNode, parentNode.typeArguments);
}
emitList(parentNode, typeParameters, 26896 /* TypeParameters */);
@@ -73532,6 +73866,9 @@ var ts;
}
if (format & 7680 /* BracketsMask */) {
writePunctuation(getOpeningBracket(format));
+ if (isEmpty) {
+ emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
+ }
}
if (onBeforeEmitNodeArray) {
onBeforeEmitNodeArray(children);
@@ -73639,6 +73976,9 @@ var ts;
onAfterEmitNodeArray(children);
}
if (format & 7680 /* BracketsMask */) {
+ if (isEmpty) {
+ emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
+ }
writePunctuation(getClosingBracket(format));
}
}
@@ -74219,7 +74559,7 @@ var ts;
if (failed) {
return "";
}
- if (!commonPathComponents) {
+ if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
return ts.getNormalizedPathFromPathComponents(commonPathComponents);
@@ -74351,8 +74691,7 @@ var ts;
}
ts.formatDiagnostics = formatDiagnostics;
function formatDiagnostic(diagnostic, host) {
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
+ var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
@@ -74377,8 +74716,9 @@ var ts;
var ellipsis = "...";
function getCategoryFormat(category) {
switch (category) {
- case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
+ case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
+ case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
}
}
@@ -74409,8 +74749,8 @@ var ts;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
- context += host.getNewLine();
for (var i = firstLine; i <= lastLine; i++) {
+ context += host.getNewLine();
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
@@ -74451,9 +74791,7 @@ var ts;
output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
output += " - ";
}
- var categoryColor = getCategoryFormat(diagnostic.category);
- var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
- output += formatColorAndReset(category, categoryColor);
+ output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file) {
@@ -75606,6 +75944,7 @@ var ts;
if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
(imports || (imports = [])).push(node.arguments[0]);
}
+ // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) {
(imports || (imports = [])).push(node.arguments[0]);
}
@@ -75706,6 +76045,7 @@ var ts;
modulesWithElidedImports.set(file_1.path, false);
processImportedModules(file_1);
}
+ // See if we need to reprocess the imports due to prior skipped imports
else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
modulesWithElidedImports.set(file_1.path, false);
@@ -76044,7 +76384,7 @@ var ts;
// 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.sourceRoot || // there is --sourceRoot specified
- options.mapRoot) {
+ options.mapRoot) { // there is --mapRoot specified
// Precalculate and cache the common source directory
var dir = getCommonSourceDirectory();
// If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
@@ -76271,7 +76611,6 @@ var ts;
if (aug.kind === 9 /* StringLiteral */) {
res.push(aug.text);
}
- // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
}
return res;
}
@@ -77275,15 +77614,17 @@ var ts;
var filesWithChangedSetOfUnresolvedImports;
var filesWithInvalidatedResolutions;
var allFilesHaveInvalidatedResolution = false;
+ var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); });
+ var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
// The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
// The key in the map is source file's path.
// The values are Map of resolutions with key being name lookedup.
var resolvedModuleNames = ts.createMap();
var perDirectoryResolvedModuleNames = ts.createMap();
+ var nonRelaticeModuleNameCache = ts.createMap();
+ var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
var resolvedTypeReferenceDirectives = ts.createMap();
var perDirectoryResolvedTypeReferenceDirectives = ts.createMap();
- var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); });
- var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
/**
* 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
@@ -77356,6 +77697,7 @@ var ts;
}
function clearPerDirectoryResolutions() {
perDirectoryResolvedModuleNames.clear();
+ nonRelaticeModuleNameCache.clear();
perDirectoryResolvedTypeReferenceDirectives.clear();
}
function finishCachingPerDirectoryResolution() {
@@ -77369,7 +77711,7 @@ var ts;
clearPerDirectoryResolutions();
}
function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
- var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host);
+ var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache);
// return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
if (!resolutionHost.getGlobalCache) {
return primaryResult;
@@ -77415,15 +77757,8 @@ var ts;
perDirectoryResolution.set(name, resolution);
}
resolutionsInFile.set(name, resolution);
- if (resolution.failedLookupLocations) {
- if (existingResolution && existingResolution.failedLookupLocations) {
- watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution);
- }
- else {
- watchFailedLookupLocationOfResolution(resolution, 0);
- }
- }
- else if (existingResolution) {
+ watchFailedLookupLocationOfResolution(resolution);
+ if (existingResolution) {
stopWatchFailedLookupLocationOfResolution(existingResolution);
}
if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
@@ -77530,78 +77865,91 @@ var ts;
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
}
- function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) {
- var failedLookupLocations = resolution.failedLookupLocations;
- var existingFailedLookupLocations = existingResolution.failedLookupLocations;
- for (var index = 0; index < failedLookupLocations.length; index++) {
- if (index === existingFailedLookupLocations.length) {
- // Additional failed lookup locations, watch from this index
- watchFailedLookupLocationOfResolution(resolution, index);
- return;
- }
- else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) {
- // Different failed lookup locations,
- // Watch new resolution failed lookup locations from this index and
- // stop watching existing resolutions from this index
- watchFailedLookupLocationOfResolution(resolution, index);
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index);
- return;
- }
+ function watchFailedLookupLocationOfResolution(resolution) {
+ // No need to set the resolution refCount
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- // All new failed lookup locations are already watched (and are same),
- // Stop watching failed lookup locations of existing resolution after failed lookup locations length
- stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length);
- }
- function watchFailedLookupLocationOfResolution(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ if (resolution.refCount !== undefined) {
+ resolution.refCount++;
+ return;
+ }
+ resolution.refCount = 1;
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var setAtRoot = false;
+ for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- // If the failed lookup location path is not one of the supported extensions,
- // store it in the custom path
- if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
- customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
- }
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore;
if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- if (dirWatcher) {
- dirWatcher.refCount++;
+ // If the failed lookup location path is not one of the supported extensions,
+ // store it in the custom path
+ if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
+ }
+ if (dirPath === rootPath) {
+ setAtRoot = true;
}
else {
- directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ setDirectoryWatcher(dir, dirPath);
}
}
}
+ if (setAtRoot) {
+ setDirectoryWatcher(rootDir, rootPath);
+ }
+ }
+ function setDirectoryWatcher(dir, dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (dirWatcher) {
+ dirWatcher.refCount++;
+ }
+ else {
+ directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ }
}
function stopWatchFailedLookupLocationOfResolution(resolution) {
- if (resolution.failedLookupLocations) {
- stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0);
+ if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) {
+ return;
}
- }
- function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) {
- var failedLookupLocations = _a.failedLookupLocations;
- for (var i = startIndex; i < failedLookupLocations.length; i++) {
- var failedLookupLocation = failedLookupLocations[i];
+ resolution.refCount--;
+ if (resolution.refCount) {
+ return;
+ }
+ var failedLookupLocations = resolution.failedLookupLocations;
+ var removeAtRoot = false;
+ for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
+ var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
- if (refCount) {
- if (refCount === 1) {
- customFailedLookupPaths.delete(failedLookupLocationPath);
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
+ if (!ignore) {
+ var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
+ if (refCount) {
+ if (refCount === 1) {
+ customFailedLookupPaths.delete(failedLookupLocationPath);
+ }
+ else {
+ ts.Debug.assert(refCount > 1);
+ customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ }
+ }
+ if (dirPath === rootPath) {
+ removeAtRoot = true;
}
else {
- ts.Debug.assert(refCount > 1);
- customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
+ removeDirectoryWatcher(dirPath);
}
}
- var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore;
- if (!ignore) {
- var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
- // Do not close the watcher yet since it might be needed by other failed lookup locations.
- dirWatcher.refCount--;
- }
}
+ if (removeAtRoot) {
+ removeDirectoryWatcher(rootPath);
+ }
+ }
+ function removeDirectoryWatcher(dirPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ // Do not close the watcher yet since it might be needed by other failed lookup locations.
+ dirWatcher.refCount--;
}
function createDirectoryWatcher(directory, dirPath) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
@@ -77802,6 +78150,7 @@ var ts;
ts.createDiagnosticReporter = createDiagnosticReporter;
function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
if (system.clearScreen &&
+ !options.preserveWatchOutput &&
diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code &&
!options.extendedDiagnostics &&
!options.diagnostics) {
@@ -78276,6 +78625,9 @@ var ts;
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
}
else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
+ if (hostSourceFileInfo.fileWatcher) {
+ hostSourceFileInfo.fileWatcher.close();
+ }
sourceFilesCache.delete(oldSourceFile.path);
resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
}
@@ -78495,6 +78847,13 @@ var ts;
category: ts.Diagnostics.Command_line_Options,
description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
},
+ {
+ name: "preserveWatchOutput",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
+ },
{
name: "watch",
shortName: "w",
@@ -78576,9 +78935,10 @@ var ts;
"es2017.string": "lib.es2017.string.d.ts",
"es2017.intl": "lib.es2017.intl.d.ts",
"es2017.typedarrays": "lib.es2017.typedarrays.d.ts",
+ "es2018.promise": "lib.es2018.promise.d.ts",
+ "es2018.regexp": "lib.es2018.regexp.d.ts",
"esnext.array": "lib.esnext.array.d.ts",
"esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
- "esnext.promise": "lib.esnext.promise.d.ts",
}),
},
showInSimplifiedHelpView: true,
@@ -80446,7 +80806,7 @@ var ts;
for (var key in opts) {
if (opts.hasOwnProperty(key)) {
var type = getOptionFromName(key);
- if (type !== undefined) {
+ if (type !== undefined) { // Ignore unknown options
out[key] = getOptionValueWithEmptyStrings(opts[key], type);
}
}
@@ -80456,11 +80816,11 @@ var ts;
ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
function getOptionValueWithEmptyStrings(value, option) {
switch (option.type) {
- case "object":// "paths". Can't get any useful information from the value since we blank out strings, so just return "".
+ case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
return "";
- case "string":// Could be any arbitrary string -- use empty string instead.
+ case "string": // Could be any arbitrary string -- use empty string instead.
return "";
- case "number":// Allow numbers, but be sure to check it's actually a number.
+ case "number": // Allow numbers, but be sure to check it's actually a number.
return typeof value === "number" ? value : "";
case "boolean":
return typeof value === "boolean" ? value : "";
@@ -80896,16 +81256,13 @@ var ts;
}
ts.getTargetLabel = getTargetLabel;
function isJumpStatementTarget(node) {
- return node.kind === 71 /* Identifier */ &&
- (node.parent.kind === 222 /* BreakStatement */ || node.parent.kind === 221 /* ContinueStatement */) &&
- node.parent.label === node;
+ return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node;
}
ts.isJumpStatementTarget = isJumpStatementTarget;
function isLabelOfLabeledStatement(node) {
- return node.kind === 71 /* Identifier */ &&
- node.parent.kind === 226 /* LabeledStatement */ &&
- node.parent.label === node;
+ return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node;
}
+ ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement;
function isLabelName(node) {
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
@@ -81271,12 +81628,7 @@ var ts;
// be parented by the container of the SyntaxList, not the SyntaxList itself.
// In order to find the list item index, we first need to locate SyntaxList itself and then search
// for the position of the relevant node (or comma).
- var syntaxList = ts.forEach(node.parent.getChildren(), function (c) {
- // find syntax list that covers the span of the node
- if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) {
- return c;
- }
- });
+ var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); });
// Either we didn't find an appropriate list, or the list must contain us.
ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node));
return syntaxList;
@@ -82031,7 +82383,7 @@ var ts;
}
function suppressTrailing(node) {
ts.addEmitFlags(node, 1024 /* NoTrailingComments */);
- var lastChild = undefined;
+ var lastChild;
ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) {
// As an optimization, jump straight to the end of the list.
if (children.length) {
@@ -82258,7 +82610,7 @@ var ts;
case 13 /* NoSubstitutionTemplateLiteral */:
return 4 /* InTemplateHeadOrNoSubstitutionTemplate */;
default:
- throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
+ return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
}
}
return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined;
@@ -82365,7 +82717,7 @@ var ts;
case 0 /* None */:
return { prefix: "" };
default:
- throw ts.Debug.assertNever(lexState);
+ return ts.Debug.assertNever(lexState);
}
}
function isBinaryExpressionOperatorToken(token) {
@@ -83212,7 +83564,7 @@ var ts;
try {
typeRoots = ts.getEffectiveTypeRoots(options, host);
}
- catch (_b) { }
+ catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ }
if (typeRoots) {
for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) {
var root = typeRoots_2[_c];
@@ -83360,7 +83712,7 @@ var ts;
try {
return ts.directoryProbablyExists(path, host);
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return undefined;
}
function tryIOAndConsumeErrors(host, toApply) {
@@ -83371,7 +83723,7 @@ var ts;
try {
return toApply && toApply.apply(host, args);
}
- catch (_a) { }
+ catch ( /*ignore*/_a) { /*ignore*/ }
return undefined;
}
})(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {}));
@@ -83422,7 +83774,7 @@ var ts;
case 3 /* JsDocParameterName */:
return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag));
default:
- throw ts.Debug.assertNever(completionData);
+ return ts.Debug.assertNever(completionData);
}
}
Completions.getCompletionsAtPosition = getCompletionsAtPosition;
@@ -83459,7 +83811,7 @@ var ts;
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
}
function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) {
- var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
+ var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
if (sourceFile.languageVariant === 1 /* JSX */ && 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.
@@ -83494,7 +83846,7 @@ var ts;
if (keywordFilters !== 0 /* None */ || !isMemberCompletion) {
ts.addRange(entries, getKeywordCompletions(keywordFilters));
}
- return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
+ return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
}
function isMemberCompletionKind(kind) {
switch (kind) {
@@ -83843,7 +84195,6 @@ var ts;
var CompletionKind;
(function (CompletionKind) {
CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration";
- /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */
CompletionKind[CompletionKind["Global"] = 1] = "Global";
CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess";
CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike";
@@ -83930,6 +84281,7 @@ var ts;
var insideComment = ts.isInComment(sourceFile, position, currentToken);
log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
var insideJsDocTagTypeExpression = false;
+ var isInSnippetScope = false;
if (insideComment) {
if (ts.hasDocComment(sourceFile, position)) {
if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
@@ -84103,7 +84455,7 @@ var ts;
getTypeScriptMemberSymbols();
}
else if (isRightOfOpenTag) {
- var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNames(), "getJsxIntrinsicTagNames() should all be defined");
+ var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
if (tryGetGlobalSymbols()) {
symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 2097152 /* Alias */)); }));
}
@@ -84130,7 +84482,7 @@ var ts;
}
log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart));
var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, position, sourceFile, typeChecker);
- return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
+ return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
case 287 /* JSDocParameterTag */:
@@ -84240,7 +84592,7 @@ var ts;
keywordFilters = 3 /* FunctionLikeBodyKeywords */;
}
// Get all entities in the current scope.
- completionKind = 5 /* None */;
+ completionKind = 1 /* Global */;
isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
if (previousToken !== contextToken) {
ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
@@ -84274,9 +84626,7 @@ var ts;
previousToken.getStart() :
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
- if (isGlobalCompletionScope(scopeNode)) {
- completionKind = 1 /* Global */;
- }
+ isInSnippetScope = isSnippetScope(scopeNode);
var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
@@ -84296,7 +84646,7 @@ var ts;
filterGlobalCompletion(symbols);
return true;
}
- function isGlobalCompletionScope(scopeNode) {
+ function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
case 272 /* SourceFile */:
case 200 /* TemplateExpression */:
@@ -84472,7 +84822,7 @@ var ts;
|| containingNodeKind === 159 /* IndexSignature */ // [ | : string ]
|| containingNodeKind === 146 /* ComputedPropertyName */; // [ | /* this can become an index signature */
case 129 /* ModuleKeyword */: // module |
- case 130 /* NamespaceKeyword */:// namespace |
+ case 130 /* NamespaceKeyword */: // namespace |
return true;
case 23 /* DotToken */:
return containingNodeKind === 237 /* ModuleDeclaration */; // module A.|
@@ -84547,7 +84897,7 @@ var ts;
isNewIdentifierLocation = false;
var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
if (!ts.isVariableLike(rootDeclaration))
- throw ts.Debug.fail("Root declaration is not variable-like.");
+ return ts.Debug.fail("Root declaration is not variable-like.");
// We don't want to complete using the type acquired by the shape
// of the binding pattern; we are only interested in types acquired
// through type declaration or inference.
@@ -84667,7 +85017,7 @@ var ts;
if (contextToken) {
switch (contextToken.kind) {
case 17 /* OpenBraceToken */: // const x = { |
- case 26 /* CommaToken */:// const x = { a: 0, |
+ case 26 /* CommaToken */: // const x = { a: 0, |
var parent = contextToken.parent;
if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) {
return parent;
@@ -84685,7 +85035,7 @@ var ts;
if (contextToken) {
switch (contextToken.kind) {
case 17 /* OpenBraceToken */: // import { |
- case 26 /* CommaToken */:// import { a as 0, |
+ case 26 /* CommaToken */: // import { a as 0, |
switch (contextToken.parent.kind) {
case 245 /* NamedImports */:
case 249 /* NamedExports */:
@@ -84713,7 +85063,7 @@ var ts;
function tryGetClassLikeCompletionContainer(contextToken) {
if (contextToken) {
switch (contextToken.kind) {
- case 17 /* OpenBraceToken */:// class c { |
+ case 17 /* OpenBraceToken */: // class c { |
if (ts.isClassLike(contextToken.parent)) {
return contextToken.parent;
}
@@ -84914,7 +85264,7 @@ var ts;
case 110 /* LetKeyword */:
case 76 /* ConstKeyword */:
case 116 /* YieldKeyword */:
- case 139 /* TypeKeyword */:// type htm|
+ case 139 /* TypeKeyword */: // type htm|
return true;
}
// If the previous token is keyword correspoding to class member completion keyword
@@ -85029,7 +85379,7 @@ var ts;
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
var name = ts.getNameOfDeclaration(m);
- existingName = ts.getEscapedTextOfIdentifierOrLiteral(name);
+ existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
existingMemberNames.set(existingName, true);
}
@@ -85133,10 +85483,10 @@ var ts;
// TODO: GH#18169
return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
case 2 /* PropertyAccess */:
- case 5 /* None */:
case 1 /* Global */:
// Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547
return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true };
+ case 5 /* None */:
case 4 /* String */:
return validIdentiferResult;
default:
@@ -85309,30 +85659,17 @@ var ts;
}
function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken);
- return referenceEntries && convertReferencedSymbols(referenceEntries);
- }
- function convertReferencedSymbols(referenceEntries) {
- var fileNameToDocumentHighlights = ts.createMap();
- for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
- var entry = referenceEntries_1[_i];
- var _a = ts.FindAllReferences.toHighlightSpan(entry), fileName = _a.fileName, span_12 = _a.span;
- var highlightSpans = fileNameToDocumentHighlights.get(fileName);
- if (!highlightSpans) {
- fileNameToDocumentHighlights.set(fileName, highlightSpans = []);
- }
- highlightSpans.push(span_12);
- }
- return ts.arrayFrom(fileNameToDocumentHighlights.entries(), function (_a) {
+ 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) {
var fileName = _a[0], highlightSpans = _a[1];
return ({ fileName: fileName, highlightSpans: highlightSpans });
});
}
function getSyntacticDocumentHighlights(node, sourceFile) {
var highlightSpans = getHighlightSpans(node, sourceFile);
- if (!highlightSpans || highlightSpans.length === 0) {
- return undefined;
- }
- return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
+ return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
}
function getHighlightSpans(node, sourceFile) {
switch (node.kind) {
@@ -85873,7 +86210,9 @@ var ts;
}
else if (ts.isDefaultImport(direct)) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(direct);
- addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports
+ if (!isAvailableThroughGlobal) {
+ addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports
+ }
directImports.push(direct);
}
else {
@@ -86025,7 +86364,7 @@ var ts;
if (propertyName) {
// This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference.
singleReferences.push(propertyName);
- if (!isForRename) {
+ if (!isForRename) { // If renaming `foo`, don't touch `bar`, just `foo`.
// Search locally for `bar`.
addSearch(name, checker.getSymbolAtLocation(name));
}
@@ -86200,12 +86539,15 @@ var ts;
return exportInfo(symbol, getExportKindForDeclaration(exportNode));
}
}
+ // If we are in `export = a;` or `export default a;`, `parent` is the export assignment.
else if (ts.isExportAssignment(parent)) {
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(parent.parent)) {
return getExportAssignmentExport(parent.parent);
}
+ // Similar for `module.exports =` and `exports.A =`.
else if (ts.isBinaryExpression(parent)) {
return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true);
}
@@ -86276,10 +86618,10 @@ var ts;
return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol));
}
var decl = importedSymbol.valueDeclaration;
- if (ts.isExportAssignment(decl)) {
+ if (ts.isExportAssignment(decl)) { // `export = class {}`
return ts.Debug.assertDefined(decl.expression.symbol);
}
- else if (ts.isBinaryExpression(decl)) {
+ else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}`
return ts.Debug.assertDefined(decl.right.symbol);
}
return ts.Debug.fail();
@@ -86356,8 +86698,8 @@ var ts;
if (parent.kind === 272 /* SourceFile */) {
return parent;
}
- ts.Debug.assert(parent.kind === 238 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent));
- return parent.parent;
+ ts.Debug.assert(parent.kind === 238 /* ModuleBlock */);
+ return ts.cast(parent.parent, isAmbientModuleDeclaration);
}
function isAmbientModuleDeclaration(node) {
return node.kind === 237 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */;
@@ -86379,12 +86721,13 @@ var ts;
}
FindAllReferences.nodeEntry = nodeEntry;
function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
- var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position);
+ var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, /*options*/ {});
var checker = program.getTypeChecker();
return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) {
var definition = _a.definition, references = _a.references;
// Only include referenced symbols that have a valid definition.
- return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) };
+ return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) };
});
}
FindAllReferences.findReferencedSymbols = findReferencedSymbols;
@@ -86420,8 +86763,8 @@ var ts;
}
}
function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) {
- var x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options));
- return ts.map(x, toReferenceEntry);
+ var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry);
}
FindAllReferences.findReferencedEntries = findReferencedEntries;
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) {
@@ -86429,46 +86772,41 @@ var ts;
return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options));
}
FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode;
- function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) {
- var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
- return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options);
- }
function flattenEntries(referenceSymbols) {
return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
}
- function definitionToReferencedSymbolDefinitionInfo(def, checker) {
+ function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
var info = (function () {
switch (def.type) {
case "symbol": {
- var symbol = def.symbol, node_3 = def.node;
- var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
+ var symbol = def.symbol;
+ var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
var name_4 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 };
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 };
}
case "label": {
- var node_4 = def.node;
- return { node: node_4, name: node_4.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_4.text, ts.SymbolDisplayPartKind.text)] };
+ var node_3 = def.node;
+ return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
}
case "keyword": {
- var node_5 = def.node;
- var name_5 = ts.tokenToString(node_5.kind);
- return { node: node_5, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ var node_4 = def.node;
+ var name_5 = ts.tokenToString(node_4.kind);
+ return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
}
case "this": {
- var node_6 = def.node;
- var symbol = checker.getSymbolAtLocation(node_6);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_6.getSourceFile(), ts.getContainerNode(node_6), node_6).displayParts;
- return { node: node_6, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
+ var node_5 = def.node;
+ var symbol = checker.getSymbolAtLocation(node_5);
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts;
+ return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
case "string": {
- var node_7 = def.node;
- return { node: node_7, name: node_7.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_7), ts.SymbolDisplayPartKind.stringLiteral)] };
+ var node_6 = def.node;
+ return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
}
+ default:
+ return ts.Debug.assertNever(def);
}
})();
- if (!info) {
- return undefined;
- }
var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts;
var sourceFile = node.getSourceFile();
return {
@@ -86481,8 +86819,10 @@ var ts;
displayParts: displayParts
};
}
- function getDefinitionKindAndDisplayParts(symbol, node, checker) {
- var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
+ function getDefinitionKindAndDisplayParts(symbol, checker, node) {
+ var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol);
+ var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node;
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
return { displayParts: displayParts, kind: symbolKind };
}
function toReferenceEntry(entry) {
@@ -86513,7 +86853,7 @@ var ts;
function implementationKindDisplayParts(node, checker) {
var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node);
if (symbol) {
- return getDefinitionKindAndDisplayParts(symbol, node, checker);
+ return getDefinitionKindAndDisplayParts(symbol, checker, node);
}
else if (node.kind === 182 /* ObjectLiteralExpression */) {
return {
@@ -86638,10 +86978,7 @@ var ts;
ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
- return [{
- definition: { type: "symbol", symbol: symbol, node: symbol.valueDeclaration },
- references: references
- }];
+ return [{ definition: { type: "symbol", symbol: symbol }, references: references }];
}
/** getReferencedSymbols for special node kinds. */
function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
@@ -86649,17 +86986,15 @@ var ts;
return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken);
}
// Labels
- if (ts.isLabelName(node)) {
- if (ts.isJumpStatementTarget(node)) {
- var labelDefinition = ts.getTargetLabel(node.parent, node.text);
- // if we have a label definition, look within its statement for references, if not, then
- // the label is undefined and we have no results..
- return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
- }
- else {
- // it is a label definition and not a target, search within the parent labeledStatement
- return getLabelReferencesInNode(node.parent, node);
- }
+ if (ts.isJumpStatementTarget(node)) {
+ var labelDefinition = ts.getTargetLabel(node.parent, node.text);
+ // if we have a label definition, look within its statement for references, if not, then
+ // the label is undefined and we have no results..
+ return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
+ }
+ else if (ts.isLabelOfLabeledStatement(node)) {
+ // it is a label definition and not a target, search within the parent labeledStatement
+ return getLabelReferencesInNode(node.parent, node);
}
if (ts.isThis(node)) {
return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
@@ -86673,11 +87008,11 @@ var ts;
function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) {
symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
// Compute the meaning from the location and the symbol it references
- var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations);
+ var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol);
var result = [];
var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result);
if (node.kind === 79 /* DefaultKeyword */) {
- addReference(node, symbol, node, state);
+ addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
else {
@@ -86781,7 +87116,11 @@ var ts;
this.symbolIdToReferences = [];
// Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
this.sourceFileToSeenSymbols = [];
+ this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; });
}
+ State.prototype.includesSourceFile = function (sourceFile) {
+ return this.includedSourceFiles.has(sourceFile.fileName);
+ };
/** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
State.prototype.getImportSearches = function (exportSymbol, exportInfo) {
if (!this.importTracker)
@@ -86795,11 +87134,11 @@ var ts;
// Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`.
// The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form
// here appears to be intentional).
- var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b;
+ var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, allSearchSymbols = searchOptions.allSearchSymbols;
var escapedText = ts.escapeLeadingUnderscores(text);
var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
return {
- location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents,
+ symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents,
includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; },
};
};
@@ -86807,12 +87146,12 @@ var ts;
* Callback to add references for a particular searched symbol.
* This initializes a reference group, so only call this if you will add at least one reference.
*/
- State.prototype.referenceAdder = function (searchSymbol, searchLocation) {
+ State.prototype.referenceAdder = function (searchSymbol) {
var symbolId = ts.getSymbolId(searchSymbol);
var references = this.symbolIdToReferences[symbolId];
if (!references) {
references = this.symbolIdToReferences[symbolId] = [];
- this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references });
+ this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references });
}
return function (node) { return references.push(FindAllReferences.nodeEntry(node)); };
};
@@ -86837,7 +87176,7 @@ var ts;
var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers;
// For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file.
if (singleReferences.length) {
- var addRef = state.referenceAdder(exportSymbol, exportLocation);
+ var addRef = state.referenceAdder(exportSymbol);
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
addRef(singleRef);
@@ -86873,7 +87212,10 @@ var ts;
function searchForImportedSymbol(symbol, state) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- getReferencesInSourceFile(declaration.getSourceFile(), state.createSearch(declaration, symbol, 0 /* Import */), state);
+ var exportingFile = declaration.getSourceFile();
+ if (state.includesSourceFile(exportingFile)) {
+ getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state);
+ }
}
}
/** Search for all occurences of an identifier in a source file (and filter out the ones that match). */
@@ -86973,6 +87315,17 @@ var ts;
// So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.)
return exposedByParent ? scope.getSourceFile() : scope;
}
+ /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
+ function isSymbolReferencedInFile(definition, checker, sourceFile) {
+ var symbol = checker.getSymbolAtLocation(definition);
+ if (!symbol)
+ return true; // Be lenient with invalid code.
+ return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) {
+ var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), ts.isIdentifier);
+ return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol;
+ });
+ }
+ Core.isSymbolReferencedInFile = isSymbolReferencedInFile;
function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) {
if (container === void 0) { container = sourceFile; }
var positions = [];
@@ -87003,18 +87356,13 @@ var ts;
return positions;
}
function getLabelReferencesInNode(container, targetLabel) {
- var references = [];
var sourceFile = container.getSourceFile();
var labelName = targetLabel.text;
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container);
- for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) {
- var position = possiblePositions_1[_i];
+ var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) {
var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
// Only pick labels that are either the target label, or have a target that is the target label
- if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) {
- references.push(FindAllReferences.nodeEntry(node));
- }
- }
+ return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined;
+ });
return [{ definition: { type: "label", node: targetLabel }, references: references }];
}
function isValidReferencePosition(node, searchSymbolName) {
@@ -87034,24 +87382,15 @@ var ts;
}
}
function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) {
- var references = [];
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
+ var references = ts.flatMap(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references);
- }
+ return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) {
+ var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined;
+ });
+ });
return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined;
}
- function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) {
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile);
- for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) {
- var position = possiblePositions_2[_i];
- var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
- if (referenceLocation.kind === kind) {
- references.push(FindAllReferences.nodeEntry(referenceLocation));
- }
- }
- }
function getReferencesInSourceFile(sourceFile, search, state) {
state.cancellationToken.throwIfCancellationRequested();
return getReferencesInContainer(sourceFile, sourceFile, search, state);
@@ -87109,7 +87448,7 @@ var ts;
}
switch (state.specialSearchKind) {
case 0 /* None */:
- addReference(referenceLocation, relatedSymbol, search.location, state);
+ addReference(referenceLocation, relatedSymbol, state);
break;
case 1 /* Constructor */:
addConstructorReferences(referenceLocation, sourceFile, search, state);
@@ -87139,7 +87478,7 @@ var ts;
addRef();
}
if (!state.options.isForRename && state.markSeenReExportRHS(name)) {
- addReference(name, referenceSymbol, name, state);
+ addReference(name, referenceSymbol, state);
}
}
else {
@@ -87161,7 +87500,7 @@ var ts;
searchForImportedSymbol(imported, state);
}
function addRef() {
- addReference(referenceLocation, localSymbol, search.location, state);
+ addReference(referenceLocation, localSymbol, state);
}
}
function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
@@ -87206,11 +87545,11 @@ var ts;
* position of property accessing, the referenceEntry of such position will be handled in the first case.
*/
if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) {
- addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state);
+ addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state);
}
}
- function addReference(referenceLocation, relatedSymbol, searchLocation, state) {
- var addRef = state.referenceAdder(relatedSymbol, searchLocation);
+ function addReference(referenceLocation, relatedSymbol, state) {
+ var addRef = state.referenceAdder(relatedSymbol);
if (state.options.implementations) {
addImplementationReferences(referenceLocation, addRef, state);
}
@@ -87221,9 +87560,9 @@ var ts;
/** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */
function addConstructorReferences(referenceLocation, sourceFile, search, state) {
if (ts.isNewExpressionTarget(referenceLocation)) {
- addReference(referenceLocation, search.symbol, search.location, state);
+ addReference(referenceLocation, search.symbol, state);
}
- var pusher = function () { return state.referenceAdder(search.symbol, search.location); };
+ var pusher = function () { return state.referenceAdder(search.symbol); };
if (ts.isClassLike(referenceLocation.parent)) {
ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation);
// This is the class declaration containing the constructor.
@@ -87238,11 +87577,11 @@ var ts;
}
}
function addClassStaticThisReferences(referenceLocation, search, state) {
- addReference(referenceLocation, search.symbol, search.location, state);
- if (ts.isClassLike(referenceLocation.parent)) {
+ addReference(referenceLocation, search.symbol, state);
+ if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) {
ts.Debug.assert(referenceLocation.parent.name === referenceLocation);
// This is the class declaration.
- addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location));
+ addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol));
}
}
function addStaticThisReferences(classLike, pusher) {
@@ -87367,7 +87706,7 @@ var ts;
return result;
}
function getContainingTypeReference(node) {
- var topLevelTypeReference = undefined;
+ var topLevelTypeReference;
while (node) {
if (ts.isTypeNode(node)) {
topLevelTypeReference = node;
@@ -87495,24 +87834,19 @@ var ts;
default:
return undefined;
}
- var references = [];
var sourceFile = searchSpaceNode.getSourceFile();
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode);
- for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) {
- var position = possiblePositions_3[_i];
+ var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) {
var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
if (!node || node.kind !== 97 /* SuperKeyword */) {
- continue;
+ return;
}
var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false);
// If we have a 'super' container, we must have an enclosing class.
// Now make sure the owning class is the same as the search-space
// and has the same static qualifier as the original 'super's owner.
- if (container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) {
- references.push(FindAllReferences.nodeEntry(node));
- }
- }
- return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol, node: superKeyword }, references: references }];
+ return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined;
+ });
+ return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }];
}
function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false);
@@ -87547,18 +87881,11 @@ var ts;
return undefined;
}
var references = [];
- var possiblePositions;
- if (searchSpaceNode.kind === 272 /* SourceFile */) {
- ts.forEach(sourceFiles, function (sourceFile) {
- cancellationToken.throwIfCancellationRequested();
- possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this");
- getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, staticFlag, references);
- });
- }
- else {
- var sourceFile = searchSpaceNode.getSourceFile();
- possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode);
- getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, references);
+ for (var _i = 0, _a = searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ cancellationToken.throwIfCancellationRequested();
+ var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode);
+ getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFile : searchSpaceNode, positions, staticFlag, references);
}
return [{
definition: { type: "this", node: thisOrSuperKeyword },
@@ -87602,26 +87929,17 @@ var ts;
});
}
function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
- var references = [];
- for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
- var sourceFile = sourceFiles_7[_i];
+ var references = ts.flatMap(sourceFiles, function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text);
- getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references);
- }
+ return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) {
+ var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false), ts.isStringLiteral);
+ return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined;
+ });
+ });
return [{
definition: { type: "string", node: node },
references: references
}];
- function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) {
- for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) {
- var position = possiblePositions_4[_i];
- var node_8 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
- if (node_8 && node_8.kind === 9 /* StringLiteral */ && node_8.text === searchText) {
- references.push(FindAllReferences.nodeEntry(node_8, /*isInString*/ true));
- }
- }
- }
}
// For certain symbol kinds, we need to include other symbols in the search set.
// This is not needed when searching for re-exports.
@@ -87838,7 +88156,9 @@ var ts;
* module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module)
* do not intersect in any of the three spaces.
*/
- function getIntersectingMeaningFromDeclarations(meaning, declarations) {
+ function getIntersectingMeaningFromDeclarations(node, symbol) {
+ var meaning = ts.getMeaningFromLocation(node);
+ var declarations = symbol.declarations;
if (declarations) {
var lastIterationMeaning = void 0;
do {
@@ -87859,6 +88179,7 @@ var ts;
}
return meaning;
}
+ Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
function isImplementation(node) {
if (!node) {
return false;
@@ -87962,9 +88283,8 @@ var ts;
}
// Labels
if (ts.isJumpStatementTarget(node)) {
- var labelName = node.text;
- var label = ts.getTargetLabel(node.parent, labelName);
- return label ? [createDefinitionInfoFromName(label, "label" /* label */, labelName, /*containerName*/ undefined)] : undefined;
+ var label = ts.getTargetLabel(node.parent, node.text);
+ return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined;
}
var typeChecker = program.getTypeChecker();
var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
@@ -88903,7 +89223,7 @@ var ts;
case 6 /* NameContainsNonURISafeCharacters */:
return "Package name '" + typing + "' contains non URI safe characters";
case 0 /* Ok */:
- throw ts.Debug.fail(); // Shouldn't have called this.
+ return ts.Debug.fail(); // Shouldn't have called this.
default:
ts.Debug.assertNever(result);
}
@@ -88929,8 +89249,8 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) {
- var sourceFile = sourceFiles_8[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
_loop_8(sourceFile);
}
rawItems.sort(compareNavigateToItems);
@@ -88990,41 +89310,35 @@ var ts;
return true;
}
function tryAddSingleDeclarationName(declaration, containers) {
- if (declaration) {
- var name = ts.getNameOfDeclaration(declaration);
- if (name) {
- var text = ts.getTextOfIdentifierOrLiteral(name);
- if (text !== undefined) {
- containers.unshift(text);
- }
- else if (name.kind === 146 /* ComputedPropertyName */) {
- return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true);
- }
- else {
- // Don't know how to add this.
- return false;
- }
- }
+ var name = ts.getNameOfDeclaration(declaration);
+ if (name && ts.isPropertyNameLiteral(name)) {
+ containers.unshift(ts.getTextOfIdentifierOrLiteral(name));
+ return true;
+ }
+ else if (name && name.kind === 146 /* ComputedPropertyName */) {
+ return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true);
+ }
+ else {
+ // Don't know how to add this.
+ return false;
}
- return true;
}
// Only added the names of computed properties if they're simple dotted expressions, like:
//
// [X.Y.Z]() { }
function tryAddComputedPropertyName(expression, containers, includeLastPortion) {
- var text = ts.getTextOfIdentifierOrLiteral(expression);
- if (text !== undefined) {
+ if (ts.isPropertyNameLiteral(expression)) {
+ var text = ts.getTextOfIdentifierOrLiteral(expression);
if (includeLastPortion) {
containers.unshift(text);
}
return true;
}
- if (expression.kind === 183 /* PropertyAccessExpression */) {
- var propertyAccess = expression;
+ if (ts.isPropertyAccessExpression(expression)) {
if (includeLastPortion) {
- containers.unshift(propertyAccess.name.text);
+ containers.unshift(expression.name.text);
}
- return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true);
+ return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true);
}
return false;
}
@@ -89663,16 +89977,20 @@ var ts;
if (node.name && ts.getFullWidth(node.name) > 0) {
return ts.declarationNameToString(node.name);
}
+ // See if it is a var initializer. If so, use the var name.
else if (node.parent.kind === 230 /* VariableDeclaration */) {
return ts.declarationNameToString(node.parent.name);
}
+ // See if it is of the form " = function(){...}". If so, use the text from the left-hand side.
else if (node.parent.kind === 198 /* BinaryExpression */ &&
node.parent.operatorToken.kind === 58 /* EqualsToken */) {
return nodeText(node.parent.left).replace(whiteSpaceRegex, "");
}
+ // See if it is a property assignment, and if so use the property name
else if (node.parent.kind === 268 /* PropertyAssignment */ && node.parent.name) {
return nodeText(node.parent.name);
}
+ // Default exports are named "default"
else if (ts.getModifierFlags(node) & 512 /* Default */) {
return "default";
}
@@ -89697,44 +90015,102 @@ var ts;
(function (ts) {
var OrganizeImports;
(function (OrganizeImports) {
- function organizeImports(sourceFile, formatContext, host) {
- // TODO (https://github.com/Microsoft/TypeScript/issues/10020): sort *within* ambient modules (find using isAmbientModule)
- // All of the old ImportDeclarations in the file, in syntactic order.
- var oldImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
- if (oldImportDecls.length === 0) {
- return [];
- }
- var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
- var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) {
- return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier);
- });
- var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
- return getExternalModuleName(importGroup[0].moduleSpecifier)
- ? coalesceImports(removeUnusedImports(importGroup))
- : importGroup;
- });
+ /**
+ * Organize imports by:
+ * 1) Removing unused imports
+ * 2) Coalescing imports from the same module
+ * 3) Sorting imports
+ */
+ function organizeImports(sourceFile, formatContext, host, program) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
- // Delete or replace the first import.
- if (newImportDecls.length === 0) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[0]);
- }
- else {
- // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
- changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: false,
- useNonAdjustedEndPosition: false,
- suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
- });
- }
- // Delete any subsequent imports.
- for (var i = 1; i < oldImportDecls.length; i++) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
+ // All of the old ImportDeclarations in the file, in syntactic order.
+ var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
+ organizeImportsWorker(topLevelImportDecls);
+ for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
+ var ambientModule = _a[_i];
+ var ambientModuleBody = getModuleBlock(ambientModule);
+ var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
+ organizeImportsWorker(ambientModuleImportDecls);
}
return changeTracker.getChanges();
+ function organizeImportsWorker(oldImportDecls) {
+ if (ts.length(oldImportDecls) === 0) {
+ return;
+ }
+ var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
+ var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
+ var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
+ return getExternalModuleName(importGroup[0].moduleSpecifier)
+ ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
+ : importGroup;
+ });
+ // Delete or replace the first import.
+ if (newImportDecls.length === 0) {
+ changeTracker.deleteNode(sourceFile, oldImportDecls[0]);
+ }
+ else {
+ // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
+ changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
+ useNonAdjustedStartPosition: false,
+ useNonAdjustedEndPosition: false,
+ suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
+ });
+ }
+ // Delete any subsequent imports.
+ for (var i = 1; i < oldImportDecls.length; i++) {
+ changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
+ }
+ }
}
OrganizeImports.organizeImports = organizeImports;
- function removeUnusedImports(oldImports) {
- return oldImports; // TODO (https://github.com/Microsoft/TypeScript/issues/10020)
+ function getModuleBlock(moduleDecl) {
+ var body = moduleDecl.body;
+ return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body));
+ }
+ function removeUnusedImports(oldImports, sourceFile, program) {
+ var typeChecker = program.getTypeChecker();
+ var jsxNamespace = typeChecker.getJsxNamespace();
+ var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx;
+ var usedImports = [];
+ for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
+ var importDecl = oldImports_1[_i];
+ var importClause = importDecl.importClause;
+ if (!importClause) {
+ // Imports without import clauses are assumed to be included for their side effects and are not removed.
+ usedImports.push(importDecl);
+ continue;
+ }
+ var name = importClause.name, namedBindings = importClause.namedBindings;
+ // Default import
+ if (name && !isDeclarationUsed(name)) {
+ name = undefined;
+ }
+ if (namedBindings) {
+ if (ts.isNamespaceImport(namedBindings)) {
+ // Namespace import
+ if (!isDeclarationUsed(namedBindings.name)) {
+ namedBindings = undefined;
+ }
+ }
+ else {
+ // List of named imports
+ var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.propertyName || e.name); });
+ if (newElements.length < namedBindings.elements.length) {
+ namedBindings = newElements.length
+ ? ts.updateNamedImports(namedBindings, newElements)
+ : undefined;
+ }
+ }
+ }
+ if (name || namedBindings) {
+ usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
+ }
+ }
+ return usedImports;
+ function isDeclarationUsed(identifier) {
+ // The JSX factory symbol is always used.
+ return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
+ }
}
function getExternalModuleName(specifier) {
return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier)
@@ -89749,7 +90125,7 @@ var ts;
if (importGroup.length === 0) {
return importGroup;
}
- var _a = getImportParts(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports;
+ var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports;
var coalescedImports = [];
if (importWithoutClause) {
coalescedImports.push(importWithoutClause);
@@ -89758,15 +90134,17 @@ var ts;
// produce two import declarations in this special case.
if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
// Add the namespace import to the existing default ImportDeclaration.
- var defaultImportClause = defaultImports[0].parent;
- coalescedImports.push(updateImportDeclarationAndClause(defaultImportClause, defaultImportClause.name, namespaceImports[0]));
+ var defaultImport = defaultImports[0];
+ coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings));
return coalescedImports;
}
- var sortedNamespaceImports = ts.stableSort(namespaceImports, function (n1, n2) { return compareIdentifiers(n1.name, n2.name); });
+ var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) {
+ return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name);
+ });
for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) {
var namespaceImport = sortedNamespaceImports_1[_i];
// Drop the name, if any
- coalescedImports.push(updateImportDeclarationAndClause(namespaceImport.parent, /*name*/ undefined, namespaceImport));
+ coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings));
}
if (defaultImports.length === 0 && namedImports.length === 0) {
return coalescedImports;
@@ -89774,30 +90152,37 @@ var ts;
var newDefaultImport;
var newImportSpecifiers = [];
if (defaultImports.length === 1) {
- newDefaultImport = defaultImports[0];
+ newDefaultImport = defaultImports[0].importClause.name;
}
else {
for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) {
var defaultImport = defaultImports_1[_b];
- newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport));
+ newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name));
}
}
- newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (n) { return n.elements; }));
+ newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
- var importClause = defaultImports.length > 0
- ? defaultImports[0].parent
- : namedImports[0].parent;
+ var importDecl = defaultImports.length > 0
+ ? defaultImports[0]
+ : namedImports[0];
var newNamedImports = sortedImportSpecifiers.length === 0
? undefined
: namedImports.length === 0
? ts.createNamedImports(sortedImportSpecifiers)
- : ts.updateNamedImports(namedImports[0], sortedImportSpecifiers);
- coalescedImports.push(updateImportDeclarationAndClause(importClause, newDefaultImport, newNamedImports));
+ : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers);
+ coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports));
return coalescedImports;
- function getImportParts(importGroup) {
+ /*
+ * Returns entire import declarations because they may already have been rewritten and
+ * may lack parent pointers. The desired parts can easily be recovered based on the
+ * categorization.
+ *
+ * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`.
+ */
+ function getCategorizedImports(importGroup) {
var importWithoutClause;
var defaultImports = [];
var namespaceImports = [];
@@ -89812,14 +90197,14 @@ var ts;
}
var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
if (name) {
- defaultImports.push(name);
+ defaultImports.push(importDeclaration);
}
if (namedBindings) {
if (ts.isNamespaceImport(namedBindings)) {
- namespaceImports.push(namedBindings);
+ namespaceImports.push(importDeclaration);
}
else {
- namedImports.push(namedBindings);
+ namedImports.push(importDeclaration);
}
}
}
@@ -89833,12 +90218,11 @@ var ts;
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseSensitive(s1.text, s2.text);
}
- function updateImportDeclarationAndClause(importClause, name, namedBindings) {
- var importDeclaration = importClause.parent;
- return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, name, namedBindings), importDeclaration.moduleSpecifier);
- }
}
OrganizeImports.coalesceImports = coalesceImports;
+ function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
+ return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
+ }
/* internal */ // Exported for testing
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
@@ -89891,8 +90275,8 @@ var ts;
continue;
}
if (!result[1]) {
- var span_13 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span_13, span_13, /*autoCollapse*/ false, result[2] || "#region"));
+ var span_12 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
+ regions.push(createOutliningSpan(span_12, span_12, /*autoCollapse*/ false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -90131,10 +90515,10 @@ var ts;
// But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
var wordSpans = getWordSpans(candidate);
for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
- var span_14 = wordSpans_1[_i];
- if (partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ true)) {
+ var span_13 = wordSpans_1[_i];
+ if (partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ true)) {
return createPatternMatch(PatternMatchKind.substring, punctuationStripped,
- /*isCaseSensitive:*/ partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ false));
+ /*isCaseSensitive:*/ partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ false));
}
}
}
@@ -90236,7 +90620,7 @@ var ts;
//
// Only if all words have some sort of match is the pattern considered matched.
var subWordTextChunks = segment.subWordTextChunks;
- var matches = undefined;
+ var matches;
for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) {
var subWordTextChunk = subWordTextChunks_1[_i];
// Try to match the candidate with this word
@@ -90284,8 +90668,8 @@ var ts;
// and I will both match in UI.
var currentCandidate = 0;
var currentChunkSpan = 0;
- var firstMatch = undefined;
- var contiguous = undefined;
+ var firstMatch;
+ var contiguous;
while (true) {
// Let's consider our termination cases
if (currentChunkSpan === chunkCharacterSpans.length) {
@@ -90585,11 +90969,18 @@ var ts;
function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
if (readImportFiles === void 0) { readImportFiles = true; }
if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
- var referencedFiles = [];
- var typeReferenceDirectives = [];
+ var pragmaContext = {
+ languageVersion: 1 /* ES5 */,
+ pragmas: undefined,
+ checkJsDirective: undefined,
+ referencedFiles: [],
+ typeReferenceDirectives: [],
+ amdDependencies: [],
+ hasNoDefaultLib: undefined,
+ moduleName: undefined
+ };
var importedFiles = [];
var ambientExternalModules;
- var isNoDefaultLib = false;
var braceNesting = 0;
// assume that text represent an external module if it contains at least one top level import/export
// ambient modules that are found inside external modules are interpreted as module augmentations
@@ -90604,23 +90995,6 @@ var ts;
}
return token;
}
- function processTripleSlashDirectives() {
- var commentRanges = ts.getLeadingCommentRanges(sourceText, 0);
- ts.forEach(commentRanges, function (commentRange) {
- var comment = sourceText.substring(commentRange.pos, commentRange.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange);
- if (referencePathMatchResult) {
- isNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var fileReference = referencePathMatchResult.fileReference;
- if (fileReference) {
- var collection = referencePathMatchResult.isTypeReferenceDirective
- ? typeReferenceDirectives
- : referencedFiles;
- collection.push(fileReference);
- }
- }
- });
- }
function getFileReference() {
var fileName = ts.scanner.getTokenValue();
var pos = ts.scanner.getTokenPos();
@@ -90881,7 +91255,8 @@ var ts;
if (readImportFiles) {
processImports();
}
- processTripleSlashDirectives();
+ ts.processCommentPragmas(pragmaContext, sourceText);
+ ts.processPragmasIntoFields(pragmaContext, ts.noop);
if (externalModule) {
// for external modules module all nested ambient modules are augmentations
if (ambientExternalModules) {
@@ -90891,7 +91266,7 @@ var ts;
importedFiles.push(decl.ref);
}
}
- return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined };
+ return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined };
}
else {
// for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
@@ -90910,7 +91285,7 @@ var ts;
}
}
}
- return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames };
+ return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
}
}
ts.preProcessFile = preProcessFile;
@@ -90941,22 +91316,17 @@ var ts;
var symbol = typeChecker.getSymbolAtLocation(node);
// Only allow a symbol to be renamed if it actually has at least one declaration.
if (symbol) {
- var declarations = symbol.getDeclarations();
+ var declarations = symbol.declarations;
if (declarations && declarations.length > 0) {
// Disallow rename for elements that are defined in the standard TypeScript library.
- if (ts.some(declarations, isDefinedInLibraryFile)) {
+ if (declarations.some(isDefinedInLibraryFile)) {
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";
- if (node.kind === 71 /* Identifier */ &&
- node.originalKeywordKind === 79 /* DefaultKeyword */ &&
- symbol.parent.flags & 1536 /* Module */) {
+ if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) {
return undefined;
}
var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
- if (!kind) {
- return undefined;
- }
var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */)
? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
: undefined;
@@ -90965,12 +91335,11 @@ var ts;
return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
}
}
- else if (node.kind === 9 /* StringLiteral */) {
+ else if (ts.isStringLiteral(node)) {
if (isDefinedInLibraryFile(node)) {
return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
}
- var displayName = ts.stripQuotes(node.text);
- return getRenameInfoSuccess(displayName, displayName, "var" /* variableElement */, "" /* none */, node, sourceFile);
+ return getRenameInfoSuccess(node.text, node.text, "var" /* variableElement */, "" /* none */, node, sourceFile);
}
}
function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
@@ -91428,6 +91797,63 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ function computeSuggestionDiagnostics(sourceFile, program) {
+ program.getSemanticDiagnostics(sourceFile);
+ var checker = program.getDiagnosticsProducingTypeChecker();
+ var diags = [];
+ if (sourceFile.commonJsModuleIndicator) {
+ diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
+ }
+ var isJsFile = ts.isSourceFileJavaScript(sourceFile);
+ function check(node) {
+ switch (node.kind) {
+ case 232 /* FunctionDeclaration */:
+ case 190 /* FunctionExpression */:
+ if (isJsFile) {
+ var symbol = node.symbol;
+ if (symbol.members && (symbol.members.size > 0)) {
+ diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
+ }
+ }
+ break;
+ }
+ if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) {
+ diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
+ }
+ node.forEachChild(check);
+ }
+ check(sourceFile);
+ if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
+ for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
+ var importNode = _a[_i];
+ var name = importNameForConvertToDefaultImport(importNode.parent);
+ if (!name)
+ continue;
+ var module = ts.getResolvedModule(sourceFile, importNode.text);
+ var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
+ if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
+ diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
+ }
+ }
+ }
+ return diags.concat(checker.getSuggestionDiagnostics(sourceFile));
+ }
+ ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
+ function importNameForConvertToDefaultImport(node) {
+ if (ts.isExternalModuleReference(node)) {
+ return node.parent.name;
+ }
+ if (ts.isImportDeclaration(node)) {
+ var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier;
+ return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier)
+ ? importClause.namedBindings.name
+ : undefined;
+ }
+ }
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var SymbolDisplay;
(function (SymbolDisplay) {
@@ -91637,7 +92063,7 @@ var ts;
}
}
else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration
- (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) {
+ (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* 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
@@ -92915,7 +93341,7 @@ var ts;
// case SyntaxKind.ConstructorDeclaration:
// case SyntaxKind.SimpleArrowFunctionExpression:
// case SyntaxKind.ParenthesizedArrowFunctionExpression:
- case 234 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one
+ case 234 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one
return true;
}
return false;
@@ -94717,26 +95143,14 @@ var ts;
function isControlFlowEndingStatement(kind, parent) {
switch (kind) {
case 223 /* ReturnStatement */:
- case 227 /* ThrowStatement */:
- switch (parent.kind) {
- case 211 /* Block */:
- var grandParent = parent.parent;
- switch (grandParent && grandParent.kind) {
- case 232 /* FunctionDeclaration */:
- case 190 /* FunctionExpression */:
- // We may want to write inner functions after this.
- return false;
- default:
- return true;
- }
- case 264 /* CaseClause */:
- case 265 /* DefaultClause */:
- case 272 /* SourceFile */:
- case 238 /* ModuleBlock */:
- return true;
- default:
- throw ts.Debug.fail();
+ case 227 /* ThrowStatement */: {
+ if (parent.kind !== 211 /* Block */) {
+ return true;
}
+ var grandParent = parent.parent;
+ // In a function, we may want to write inner functions after this.
+ return !(grandParent && grandParent.kind === 190 /* FunctionExpression */ || grandParent.kind === 232 /* FunctionDeclaration */);
+ }
case 221 /* ContinueStatement */:
case 222 /* BreakStatement */:
return true;
@@ -94874,10 +95288,9 @@ var ts;
}
var ChangeTracker = /** @class */ (function () {
/** Public for tests only. Other callers should use `ChangeTracker.with`. */
- function ChangeTracker(newLineCharacter, formatContext, validator) {
+ function ChangeTracker(newLineCharacter, formatContext) {
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
- this.validator = validator;
this.changes = [];
this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
// Map from class id to nodes to insert at the start
@@ -95016,10 +95429,10 @@ var ts;
if (ts.isStatement(before) || ts.isClassElement(before)) {
return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
}
- else if (ts.isVariableDeclaration(before)) {
+ else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2;
return { suffix: ", " };
}
- throw ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
+ return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
};
ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
var firstStatement = ts.firstOrUndefined(ctr.body.statements);
@@ -95096,7 +95509,7 @@ var ts;
else if (ts.isVariableDeclaration(node)) {
return { prefix: ", " };
}
- throw ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it
+ return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it
};
/**
* This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
@@ -95247,92 +95660,83 @@ var ts;
_this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true });
});
};
- ChangeTracker.prototype.getChanges = function () {
- var _this = this;
+ /**
+ * Note: after calling this, the TextChanges object must be discarded!
+ * @param validate only for tests
+ * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions,
+ * so we can only call this once and can't get the non-formatted text separately.
+ */
+ ChangeTracker.prototype.getChanges = function (validate) {
this.finishInsertNodeAtClassStart();
- return ts.group(this.changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
- var sourceFile = changesInFile[0].sourceFile;
- var textChanges = ChangeTracker.normalize(changesInFile).map(function (c) {
- return ts.createTextChange(ts.createTextSpanFromRange(c.range), _this.computeNewText(c, sourceFile));
- });
- return { fileName: sourceFile.fileName, textChanges: textChanges };
- });
- };
- ChangeTracker.prototype.computeNewText = function (change, sourceFile) {
- var _this = this;
- if (change.kind === ChangeKind.Remove) {
- // deletion case
- return "";
- }
- var options = change.options || {};
- var text;
- var pos = change.range.pos;
- var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos;
- if (change.kind === ChangeKind.ReplaceWithMultipleNodes) {
- var lastIndex_1 = change.nodes.length - 1;
- var parts = change.nodes.map(function (n, index) {
- var formatted = _this.getFormattedTextOfNode(n, sourceFile, pos, options);
- return index === lastIndex_1 || ts.endsWith(formatted, _this.newLineCharacter)
- ? formatted
- : (formatted + _this.newLineCharacter);
- });
- text = parts.join("");
- }
- else {
- ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode");
- text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options);
- }
- // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
- text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, "");
- return (options.prefix || "") + text + (options.suffix || "");
- };
- ChangeTracker.prototype.getFormattedTextOfNode = function (node, sourceFile, pos, options) {
- var nonformattedText = getNonformattedText(node, sourceFile, this.newLineCharacter);
- if (this.validator) {
- this.validator(nonformattedText);
- }
- var formatOptions = this.formatContext.options;
- var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos;
- var initialIndentation = options.indentation !== undefined
- ? options.indentation
- : (options.useIndentationFromFile !== false)
- ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, posStartsLine || (options.prefix === this.newLineCharacter))
- : 0;
- var delta = options.delta !== undefined
- ? options.delta
- : ts.formatting.SmartIndenter.shouldIndentChildNode(node)
- ? (formatOptions.indentSize || 0)
- : 0;
- return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.formatContext);
- };
- ChangeTracker.normalize = function (changes) {
- // order changes by start position
- var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; });
- // verify that change intervals do not overlap, except possibly at end points.
- for (var i = 0; i < normalized.length - 2; i++) {
- ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos);
- }
- return normalized;
+ return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
};
return ChangeTracker;
}());
textChanges_1.ChangeTracker = ChangeTracker;
- function getNonformattedText(node, sourceFile, newLine) {
- var writer = new Writer(newLine);
- var printer = ts.createPrinter({ newLine: newLine === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */ }, writer);
- printer.writeNode(4 /* Unspecified */, node, sourceFile, writer);
- return { text: writer.getText(), node: assignPositionsToNode(node) };
- }
- function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, formatContext) {
- var lineMap = ts.computeLineStarts(nonFormattedText.text);
- var file = {
- text: nonFormattedText.text,
- lineMap: lineMap,
- getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); }
- };
- var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext);
- return applyChanges(nonFormattedText.text, changes);
- }
+ var changesToText;
+ (function (changesToText) {
+ function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
+ return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
+ var sourceFile = changesInFile[0].sourceFile;
+ // order changes by start position
+ var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
+ var _loop_10 = 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 - 2; i++) {
+ _loop_10(i);
+ }
+ var textChanges = normalized.map(function (c) {
+ return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
+ });
+ return { fileName: sourceFile.fileName, textChanges: textChanges };
+ });
+ }
+ changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
+ if (change.kind === ChangeKind.Remove) {
+ return "";
+ }
+ var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos;
+ var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); };
+ var text = change.kind === ChangeKind.ReplaceWithMultipleNodes
+ ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter)
+ : format(change.node);
+ // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
+ var noIndent = (options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, "");
+ return (options.prefix || "") + noIndent + (options.suffix || "");
+ }
+ /** Note: this may mutate `nodeIn`. */
+ function getFormattedTextOfNode(nodeIn, sourceFile, pos, options, newLineCharacter, formatContext, validate) {
+ var _a = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _a.node, text = _a.text;
+ if (validate)
+ validate(node, text);
+ var formatOptions = formatContext.options;
+ var initialIndentation = options.indentation !== undefined
+ ? options.indentation
+ : (options.useIndentationFromFile !== false)
+ ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, options.prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos)
+ : 0;
+ var delta = options.delta !== undefined
+ ? options.delta
+ : ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn)
+ ? (formatOptions.indentSize || 0)
+ : 0;
+ var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } };
+ var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext);
+ return applyChanges(text, changes);
+ }
+ /** Note: output node may be mutated input node. */
+ function getNonformattedText(node, sourceFile, newLineCharacter) {
+ var writer = new Writer(newLineCharacter);
+ var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */;
+ ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer);
+ return { text: writer.getText(), node: assignPositionsToNode(node) };
+ }
+ })(changesToText || (changesToText = {}));
function applyChanges(text, changes) {
for (var i = changes.length - 1; i >= 0; i--) {
var change = changes[i];
@@ -95611,7 +96015,7 @@ var ts;
codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges;
function eachDiagnostic(_a, errorCodes, cb) {
var program = _a.program, sourceFile = _a.sourceFile;
- for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) {
+ for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) {
var diag = _b[_i];
if (ts.contains(errorCodes, diag.code)) {
cb(diag);
@@ -95677,6 +96081,831 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "annotateWithTypeFromJSDoc";
+ var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var decl = getDeclaration(context.sourceFile, context.span.start);
+ if (!decl)
+ return;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Annotate_with_type_from_JSDoc);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); });
+ return [{ description: description, changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var decl = getDeclaration(diag.file, diag.start);
+ if (decl)
+ doChange(changes, diag.file, decl);
+ }); },
+ });
+ function getDeclaration(file, pos) {
+ var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false);
+ // For an arrow function with no name, 'name' lands on the first parameter.
+ return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
+ }
+ function parameterShouldGetTypeFromJSDoc(node) {
+ return isDeclarationWithType(node) && hasUsableJSDoc(node);
+ }
+ codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc;
+ function hasUsableJSDoc(decl) {
+ return ts.isFunctionLikeDeclaration(decl)
+ ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl))
+ : !decl.type && !!ts.getJSDocType(decl);
+ }
+ function doChange(changes, sourceFile, decl) {
+ if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
+ ts.findAncestor(decl, ts.isFunctionLike);
+ var fn = ts.findAncestor(decl, ts.isFunctionLikeDeclaration);
+ var functionWithType = addTypesToFunctionLike(fn);
+ ts.suppressLeadingAndTrailingTrivia(functionWithType);
+ changes.replaceNode(sourceFile, fn, functionWithType, ts.textChanges.useNonAdjustedPositions);
+ return;
+ }
+ else {
+ var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix
+ ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix.
+ var declarationWithType = addType(decl, transformJSDocType(jsdocType));
+ ts.suppressLeadingAndTrailingTrivia(declarationWithType);
+ changes.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions);
+ }
+ }
+ function isDeclarationWithType(node) {
+ return ts.isFunctionLikeDeclaration(node) ||
+ node.kind === 230 /* VariableDeclaration */ ||
+ node.kind === 150 /* PropertySignature */ ||
+ node.kind === 151 /* PropertyDeclaration */;
+ }
+ function addTypesToFunctionLike(decl) {
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, /*checkJSDoc*/ true);
+ var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, /*checkJSDoc*/ true)), p.initializer); });
+ var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, /*checkJSDoc*/ true));
+ switch (decl.kind) {
+ case 232 /* FunctionDeclaration */:
+ return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
+ case 154 /* Constructor */:
+ return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body);
+ case 190 /* FunctionExpression */:
+ return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
+ case 191 /* ArrowFunction */:
+ return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body);
+ case 153 /* MethodDeclaration */:
+ return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body);
+ case 155 /* GetAccessor */:
+ return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body);
+ case 156 /* SetAccessor */:
+ return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body);
+ default:
+ return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind);
+ }
+ }
+ function addType(decl, jsdocType) {
+ switch (decl.kind) {
+ case 230 /* VariableDeclaration */:
+ return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer);
+ case 150 /* PropertySignature */:
+ return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
+ case 151 /* PropertyDeclaration */:
+ return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
+ default:
+ return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind);
+ }
+ }
+ function transformJSDocType(node) {
+ if (node === undefined) {
+ return undefined;
+ }
+ switch (node.kind) {
+ case 275 /* JSDocAllType */:
+ case 276 /* JSDocUnknownType */:
+ return ts.createTypeReferenceNode("any", ts.emptyArray);
+ case 279 /* JSDocOptionalType */:
+ return transformJSDocOptionalType(node);
+ case 278 /* JSDocNonNullableType */:
+ return transformJSDocType(node.type);
+ case 277 /* JSDocNullableType */:
+ return transformJSDocNullableType(node);
+ case 281 /* JSDocVariadicType */:
+ return transformJSDocVariadicType(node);
+ case 280 /* JSDocFunctionType */:
+ return transformJSDocFunctionType(node);
+ case 148 /* Parameter */:
+ return transformJSDocParameter(node);
+ case 161 /* TypeReference */:
+ return transformJSDocTypeReference(node);
+ default:
+ var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined);
+ ts.setEmitFlags(visited, 1 /* SingleLine */);
+ return visited;
+ }
+ }
+ function transformJSDocOptionalType(node) {
+ return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
+ }
+ function transformJSDocNullableType(node) {
+ return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
+ }
+ function transformJSDocVariadicType(node) {
+ return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
+ }
+ function transformJSDocFunctionType(node) {
+ var parameters = node.parameters && node.parameters.map(transformJSDocType);
+ return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type);
+ }
+ function transformJSDocParameter(node) {
+ var index = node.parent.parameters.indexOf(node);
+ var isRest = node.type.kind === 281 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
+ var name = node.name || (isRest ? "rest" : "arg" + index);
+ var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
+ return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
+ }
+ function transformJSDocTypeReference(node) {
+ var name = node.typeName;
+ var args = node.typeArguments;
+ if (ts.isIdentifier(node.typeName)) {
+ if (ts.isJSDocIndexSignature(node)) {
+ return transformJSDocIndexSignature(node);
+ }
+ var text = node.typeName.text;
+ switch (node.typeName.text) {
+ case "String":
+ case "Boolean":
+ case "Object":
+ case "Number":
+ text = text.toLowerCase();
+ break;
+ case "array":
+ case "date":
+ case "promise":
+ text = text[0].toUpperCase() + text.slice(1);
+ break;
+ }
+ name = ts.createIdentifier(text);
+ if ((text === "Array" || text === "Promise") && !node.typeArguments) {
+ args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
+ }
+ else {
+ args = ts.visitNodes(node.typeArguments, transformJSDocType);
+ }
+ }
+ return ts.createTypeReferenceNode(name, args);
+ }
+ function transformJSDocIndexSignature(node) {
+ var index = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s",
+ /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []),
+ /*initializer*/ undefined);
+ var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
+ ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
+ return indexSignature;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "convertFunctionToEs6Class";
+ var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
+ return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_function_to_an_ES2015_class), changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
+ });
+ function doChange(changes, sourceFile, position, checker) {
+ var deletedNodes = [];
+ var deletes = [];
+ var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false));
+ if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
+ // Bad input
+ return undefined;
+ }
+ var ctorDeclaration = ctorSymbol.valueDeclaration;
+ var precedingNode;
+ var newClassDeclaration;
+ switch (ctorDeclaration.kind) {
+ case 232 /* FunctionDeclaration */:
+ precedingNode = ctorDeclaration;
+ deleteNode(ctorDeclaration);
+ newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
+ break;
+ case 230 /* VariableDeclaration */:
+ precedingNode = ctorDeclaration.parent.parent;
+ if (ctorDeclaration.parent.declarations.length === 1) {
+ deleteNode(precedingNode);
+ }
+ else {
+ deleteNode(ctorDeclaration, /*inList*/ true);
+ }
+ newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
+ break;
+ }
+ if (!newClassDeclaration) {
+ return undefined;
+ }
+ // Because the preceding node could be touched, we need to insert nodes before delete nodes.
+ changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
+ for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) {
+ var deleteCallback = deletes_1[_i];
+ deleteCallback();
+ }
+ function deleteNode(node, inList) {
+ if (inList === void 0) { inList = false; }
+ if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) {
+ // Parent node has already been deleted; do nothing
+ return;
+ }
+ deletedNodes.push(node);
+ if (inList) {
+ deletes.push(function () { return changes.deleteNodeInList(sourceFile, node); });
+ }
+ else {
+ deletes.push(function () { return changes.deleteNode(sourceFile, node); });
+ }
+ }
+ function createClassElementsFromSymbol(symbol) {
+ var memberElements = [];
+ // all instance members are stored in the "member" array of symbol
+ if (symbol.members) {
+ symbol.members.forEach(function (member) {
+ var memberElement = createClassElement(member, /*modifiers*/ undefined);
+ if (memberElement) {
+ memberElements.push(memberElement);
+ }
+ });
+ }
+ // all static members are stored in the "exports" array of symbol
+ if (symbol.exports) {
+ symbol.exports.forEach(function (member) {
+ var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]);
+ if (memberElement) {
+ memberElements.push(memberElement);
+ }
+ });
+ }
+ return memberElements;
+ function shouldConvertDeclaration(_target, source) {
+ // Right now the only thing we can convert are function expressions - other values shouldn't get
+ // transformed. We can update this once ES public class properties are available.
+ return ts.isFunctionLike(source);
+ }
+ function createClassElement(symbol, modifiers) {
+ // both properties and methods are bound as property symbols
+ if (!(symbol.flags & 4 /* Property */)) {
+ return;
+ }
+ var memberDeclaration = symbol.valueDeclaration;
+ var assignmentBinaryExpression = memberDeclaration.parent;
+ if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
+ return;
+ }
+ // 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 === 214 /* ExpressionStatement */
+ ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
+ deleteNode(nodeToDelete);
+ if (!assignmentBinaryExpression.right) {
+ return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
+ /*type*/ undefined, /*initializer*/ undefined);
+ }
+ switch (assignmentBinaryExpression.right.kind) {
+ case 190 /* FunctionExpression */: {
+ var functionExpression = assignmentBinaryExpression.right;
+ var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */));
+ var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
+ /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
+ copyComments(assignmentBinaryExpression, method, sourceFile);
+ return method;
+ }
+ case 191 /* ArrowFunction */: {
+ var arrowFunction = assignmentBinaryExpression.right;
+ var arrowFunctionBody = arrowFunction.body;
+ var bodyBlock = void 0;
+ // case 1: () => { return [1,2,3] }
+ if (arrowFunctionBody.kind === 211 /* Block */) {
+ bodyBlock = arrowFunctionBody;
+ }
+ // case 2: () => [1,2,3]
+ else {
+ bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
+ }
+ var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */));
+ var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
+ /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
+ copyComments(assignmentBinaryExpression, method, sourceFile);
+ return method;
+ }
+ default: {
+ // Don't try to declare members in JavaScript files
+ if (ts.isSourceFileJavaScript(sourceFile)) {
+ return;
+ }
+ var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
+ /*type*/ undefined, assignmentBinaryExpression.right);
+ copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ return prop;
+ }
+ }
+ }
+ }
+ function createClassFromVariableDeclaration(node) {
+ var initializer = node.initializer;
+ if (!initializer || initializer.kind !== 190 /* FunctionExpression */) {
+ return undefined;
+ }
+ if (node.name.kind !== 71 /* Identifier */) {
+ return undefined;
+ }
+ var memberElements = createClassElementsFromSymbol(initializer.symbol);
+ if (initializer.body) {
+ memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
+ }
+ var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */);
+ var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
+ /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
+ // Don't call copyComments here because we'll already leave them in place
+ return cls;
+ }
+ function createClassFromFunctionDeclaration(node) {
+ var memberElements = createClassElementsFromSymbol(ctorSymbol);
+ if (node.body) {
+ memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
+ }
+ var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */);
+ var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
+ /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
+ // Don't call copyComments here because we'll already leave them in place
+ return cls;
+ }
+ }
+ function copyComments(sourceNode, targetNode, sourceFile) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ if (kind === 3 /* MultiLineCommentTrivia */) {
+ // Remove leading /*
+ pos += 2;
+ // Remove trailing */
+ end -= 2;
+ }
+ else {
+ // Remove leading //
+ pos += 2;
+ }
+ ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl);
+ });
+ }
+ function getModifierKindFromSource(source, kind) {
+ return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code],
+ getCodeActions: function (context) {
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module);
+ var sourceFile = context.sourceFile, program = context.program;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
+ var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target);
+ if (moduleExportsChangedToDefault) {
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var importingFile = _a[_i];
+ fixImportOfModuleExports(importingFile, sourceFile, changes);
+ }
+ }
+ });
+ // No support for fix-all since this applies to the whole file at once anyway.
+ return [{ description: description, changes: changes, fixId: undefined }];
+ },
+ });
+ function fixImportOfModuleExports(importingFile, exportingFile, changes) {
+ for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
+ var moduleSpecifier = _a[_i];
+ var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
+ if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
+ continue;
+ }
+ var parent = moduleSpecifier.parent;
+ switch (parent.kind) {
+ case 252 /* ExternalModuleReference */: {
+ var importEq = parent.parent;
+ changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text));
+ break;
+ }
+ case 185 /* CallExpression */: {
+ var call = parent;
+ if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) {
+ changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default"));
+ }
+ break;
+ }
+ }
+ }
+ }
+ /** @returns Whether we converted a `module.exports =` to a default export. */
+ function convertFileToEs6Module(sourceFile, checker, changes, target) {
+ var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
+ var exports = collectExportRenames(sourceFile, checker, identifiers);
+ convertExportsAccesses(sourceFile, exports, changes);
+ var moduleExportsChangedToDefault = false;
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports);
+ moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
+ }
+ return moduleExportsChangedToDefault;
+ }
+ function collectExportRenames(sourceFile, checker, identifiers) {
+ var res = ts.createMap();
+ forEachExportReference(sourceFile, function (node) {
+ var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
+ if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
+ || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) {
+ // Unconditionally add an underscore in case `text` is a keyword.
+ res.set(text, makeUniqueName("_" + text, identifiers));
+ }
+ });
+ return res;
+ }
+ function convertExportsAccesses(sourceFile, exports, changes) {
+ forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
+ if (isAssignmentLhs) {
+ return;
+ }
+ var text = node.name.text;
+ changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
+ });
+ }
+ function forEachExportReference(sourceFile, cb) {
+ sourceFile.forEachChild(function recur(node) {
+ if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
+ var parent = node.parent;
+ cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */);
+ }
+ node.forEachChild(recur);
+ });
+ }
+ function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) {
+ switch (statement.kind) {
+ case 212 /* VariableStatement */:
+ convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target);
+ return false;
+ case 214 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ switch (expression.kind) {
+ case 185 /* CallExpression */: {
+ if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) {
+ // For side-effecting require() call, just make a side-effecting import.
+ changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text));
+ }
+ return false;
+ }
+ case 198 /* BinaryExpression */: {
+ var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
+ return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports);
+ }
+ }
+ }
+ // falls through
+ default:
+ return false;
+ }
+ }
+ function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) {
+ var declarationList = statement.declarationList;
+ var foundImport = false;
+ var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
+ var name = decl.name, initializer = decl.initializer;
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
+ // `const alias = module.exports;` can be removed.
+ foundImport = true;
+ return [];
+ }
+ if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) {
+ foundImport = true;
+ return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target);
+ }
+ else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) {
+ foundImport = true;
+ return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers);
+ }
+ else {
+ // Move it out to its own variable statement.
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
+ }
+ });
+ if (foundImport) {
+ // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ }
+ }
+ /** Converts `const name = require("moduleSpecifier").propertyName` */
+ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) {
+ switch (name.kind) {
+ case 178 /* ObjectBindingPattern */:
+ case 179 /* ArrayBindingPattern */: {
+ // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
+ var tmp = makeUniqueName(propertyName, identifiers);
+ return [
+ makeSingleImport(tmp, propertyName, moduleSpecifier),
+ makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
+ ];
+ }
+ case 71 /* Identifier */:
+ // `const a = require("b").c` --> `import { c as a } from "./b";
+ return [makeSingleImport(name.text, propertyName, moduleSpecifier)];
+ default:
+ ts.Debug.assertNever(name);
+ }
+ }
+ function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) {
+ if (!ts.isPropertyAccessExpression(left)) {
+ return false;
+ }
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
+ if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
+ // `const alias = module.exports;` or `module.exports = alias;` can be removed.
+ changes.deleteNode(sourceFile, statement);
+ }
+ else {
+ var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
+ var changedToDefaultExport = false;
+ if (!newNodes) {
+ (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ }
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ return changedToDefaultExport;
+ }
+ }
+ else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
+ convertNamedExport(sourceFile, statement, left.name, right, changes, exports);
+ }
+ return false;
+ var _a;
+ }
+ /**
+ * Convert `module.exports = { ... }` to individual exports..
+ * We can't always do this if the module has interesting members -- then it will be a default export instead.
+ */
+ function tryChangeModuleExportsObject(object) {
+ return ts.mapAllOrFail(object.properties, function (prop) {
+ switch (prop.kind) {
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
+ case 269 /* ShorthandPropertyAssignment */:
+ case 270 /* SpreadAssignment */:
+ return undefined;
+ case 268 /* PropertyAssignment */:
+ return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer);
+ case 153 /* MethodDeclaration */:
+ return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop);
+ default:
+ ts.Debug.assertNever(prop);
+ }
+ });
+ }
+ function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) {
+ // If "originalKeywordKind" was set, this is e.g. `exports.
+ var text = propertyName.text;
+ var rename = exports.get(text);
+ if (rename !== undefined) {
+ /*
+ const _class = 0;
+ export { _class as class };
+ */
+ var newNodes = [
+ makeConst(/*modifiers*/ undefined, rename, right),
+ makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
+ ];
+ changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
+ }
+ else {
+ changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true });
+ }
+ }
+ function convertModuleExportsToExportDefault(exported, checker) {
+ var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
+ switch (exported.kind) {
+ case 190 /* FunctionExpression */:
+ case 191 /* ArrowFunction */: {
+ // `module.exports = function f() {}` --> `export default function f() {}`
+ var fn = exported;
+ return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
+ }
+ case 203 /* ClassExpression */: {
+ // `module.exports = class C {}` --> `export default class C {}`
+ var cls = exported;
+ return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
+ }
+ case 185 /* CallExpression */:
+ if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) {
+ return convertReExportAll(exported.arguments[0], checker);
+ }
+ // falls through
+ default:
+ // `module.exports = 0;` --> `export default 0;`
+ return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
+ }
+ }
+ function convertReExportAll(reExported, checker) {
+ // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
+ var moduleSpecifier = reExported.text;
+ var moduleSymbol = checker.getSymbolAtLocation(reExported);
+ var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
+ return exports.has("export=")
+ ? [[reExportDefault(moduleSpecifier)], true]
+ : !exports.has("default")
+ ? [[reExportStar(moduleSpecifier)], false]
+ // If there's some non-default export, must include both `export *` and `export default`.
+ : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
+ }
+ function reExportStar(moduleSpecifier) {
+ return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
+ }
+ function reExportDefault(moduleSpecifier) {
+ return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
+ }
+ function convertExportsDotXEquals(name, exported) {
+ var modifiers = [ts.createToken(84 /* ExportKeyword */)];
+ switch (exported.kind) {
+ case 190 /* FunctionExpression */: {
+ var expressionName = exported.name;
+ if (expressionName && expressionName.text !== name) {
+ // `exports.f = function g() {}` -> `export const f = function g() {}`
+ return exportConst();
+ }
+ }
+ // falls through
+ case 191 /* ArrowFunction */:
+ // `exports.f = function() {}` --> `export function f() {}`
+ return functionExpressionToDeclaration(name, modifiers, exported);
+ case 203 /* ClassExpression */:
+ // `exports.C = class {}` --> `export class C {}`
+ return classExpressionToDeclaration(name, modifiers, exported);
+ default:
+ return exportConst();
+ }
+ function exportConst() {
+ // `exports.x = 0;` --> `export const x = 0;`
+ return makeConst(modifiers, ts.createIdentifier(name), exported);
+ }
+ }
+ /**
+ * Converts `const <> = require("x");`.
+ * Returns nodes that will replace the variable declaration for the commonjs import.
+ * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
+ */
+ function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) {
+ switch (name.kind) {
+ case 178 /* 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
+ : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
+ });
+ if (importSpecifiers) {
+ return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
+ }
+ }
+ // falls through -- object destructuring has an interesting pattern and must be a variable declaration
+ case 179 /* ArrayBindingPattern */: {
+ /*
+ import x from "x";
+ const [a, b, c] = x;
+ */
+ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers);
+ return [
+ makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
+ makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
+ ];
+ }
+ case 71 /* Identifier */:
+ return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers);
+ default:
+ ts.Debug.assertNever(name);
+ }
+ }
+ /**
+ * Convert `import x = require("x").`
+ * Also converts uses like `x.y()` to `y()` and uses a named import.
+ */
+ function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) {
+ var nameSymbol = checker.getSymbolAtLocation(name);
+ // Maps from module property name to name actually used. (The same if there isn't shadowing.)
+ var namedBindingsNames = ts.createMap();
+ // True if there is some non-property use like `x()` or `f(x)`.
+ var needDefaultImport = false;
+ for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
+ var use = _a[_i];
+ if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
+ // This was a use of a different symbol with the same name, due to shadowing. Ignore.
+ continue;
+ }
+ var parent = use.parent;
+ if (ts.isPropertyAccessExpression(parent)) {
+ var expression = parent.expression, propertyName = parent.name.text;
+ ts.Debug.assert(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);
+ }
+ changes.replaceNode(file, parent, ts.createIdentifier(idName));
+ }
+ else {
+ needDefaultImport = true;
+ }
+ }
+ var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
+ var propertyName = _a[0], idName = _a[1];
+ return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
+ }));
+ if (!namedBindings) {
+ // If it was unused, ensure that we at least import *something*.
+ needDefaultImport = true;
+ }
+ return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ }
+ // Identifiers helpers
+ function makeUniqueName(name, identifiers) {
+ while (identifiers.original.has(name) || identifiers.additional.has(name)) {
+ name = "_" + name;
+ }
+ identifiers.additional.set(name, true);
+ return name;
+ }
+ function collectFreeIdentifiers(file) {
+ var map = ts.createMultiMap();
+ file.forEachChild(function recur(node) {
+ if (ts.isIdentifier(node) && isFreeIdentifier(node)) {
+ map.add(node.text, node);
+ }
+ node.forEachChild(recur);
+ });
+ return map;
+ }
+ function isFreeIdentifier(node) {
+ var parent = node.parent;
+ switch (parent.kind) {
+ case 183 /* PropertyAccessExpression */:
+ return parent.name !== node;
+ case 180 /* BindingElement */:
+ return parent.propertyName !== node;
+ default:
+ return true;
+ }
+ }
+ // Node helpers
+ function functionExpressionToDeclaration(name, additionalModifiers, fn) {
+ return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
+ ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
+ }
+ function classExpressionToDeclaration(name, additionalModifiers, cls) {
+ return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
+ ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
+ }
+ function makeSingleImport(localName, propertyName, moduleSpecifier) {
+ return propertyName === "default"
+ ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
+ : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ }
+ function makeImport(name, namedImports, moduleSpecifier) {
+ return makeImportDeclaration(name, namedImports, ts.createLiteral(moduleSpecifier));
+ }
+ function makeImportDeclaration(name, namedImports, moduleSpecifier) {
+ var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
+ return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier);
+ }
+ codefix.makeImportDeclaration = makeImportDeclaration;
+ function makeImportSpecifier(propertyName, name) {
+ return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
+ }
+ function makeConst(modifiers, name, init) {
+ return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
+ }
+ function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
+ return ts.createExportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -95749,9 +96978,7 @@ var ts;
},
});
function getClass(sourceFile, pos) {
- var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false));
- ts.Debug.assert(!!classDeclaration);
- return classDeclaration;
+ return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)));
}
function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) {
// Note that this is ultimately derived from a map indexed by symbol names,
@@ -96059,7 +97286,6 @@ var ts;
commands: [getCommand(fileName, packageName)],
};
}
- codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes;
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
@@ -96082,17 +97308,21 @@ var ts;
return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }];
},
fixIds: [fixId],
- getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
- addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes);
- }); },
+ getAllCodeActions: function (context) {
+ var seenClassDeclarations = ts.createMap();
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var classDeclaration = getClass(diag.file, diag.start);
+ if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
+ addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes);
+ }
+ });
+ },
});
function getClass(sourceFile, pos) {
- // This is the identifier in the case of a class declaration
+ // Token is the identifier in the case of a class declaration
// or the class keyword token in the case of a class expression.
var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
- var classDeclaration = token.parent;
- ts.Debug.assert(ts.isClassLike(classDeclaration));
- return classDeclaration;
+ return ts.cast(token.parent, ts.isClassLike);
}
function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) {
var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration);
@@ -96432,9 +97662,9 @@ var ts;
changes.deleteNodeInList(sourceFile, parent);
}
break;
- case 243 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *'
+ case 243 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *'
var importClause = parent;
- if (!importClause.namedBindings) {
+ if (!importClause.namedBindings) { // |import d from './file'|
changes.deleteNode(sourceFile, ts.getAncestor(importClause, 242 /* ImportDeclaration */));
}
else {
@@ -96800,7 +98030,7 @@ var ts;
case 252 /* ExternalModuleReference */:
return parent.parent;
case 248 /* ExportDeclaration */:
- case 185 /* CallExpression */:// For "require()" calls
+ case 185 /* CallExpression */: // For "require()" calls
// Ignore these, can't add imports to them.
return undefined;
default:
@@ -97219,7 +98449,7 @@ var ts;
var parent = token.parent;
var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent);
if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258 /* JsxOpeningFragment */) {
- umdSymbol = checker.resolveName(checker.getJsxNamespace(), isNodeOpeningLikeElement ? parent.tagName : parent, 107455 /* Value */, /*excludeGlobals*/ false);
+ umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 107455 /* Value */, /*excludeGlobals*/ false);
}
}
if (ts.isUMDExportSymbol(umdSymbol)) {
@@ -97249,7 +98479,7 @@ var ts;
// Fall back to the `import * as ns` style import.
return 2 /* Namespace */;
default:
- throw ts.Debug.assertNever(moduleKind);
+ return ts.Debug.assertNever(moduleKind);
}
}
function getActionsForNonUMDImport(context) {
@@ -97719,7 +98949,7 @@ var ts;
case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, program, cancellationToken) : undefined;
default:
- throw ts.Debug.fail(String(errorCode));
+ return ts.Debug.fail(String(errorCode));
}
}
function isAllowedTokenKind(kind) {
@@ -97889,13 +99119,13 @@ var ts;
var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
return callContexts && declaration.parameters.map(function (parameter, parameterIndex) {
var types = [];
- var isRestParameter = ts.isRestParameter(parameter);
+ var isRest = ts.isRestParameter(parameter);
for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) {
var callContext = callContexts_1[_i];
if (callContext.argumentTypes.length <= parameterIndex) {
continue;
}
- if (isRestParameter) {
+ if (isRest) {
for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) {
types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i]));
}
@@ -97908,7 +99138,7 @@ var ts;
return undefined;
}
var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */));
- return isRestParameter ? checker.createArrayType(type) : type;
+ return isRest ? checker.createArrayType(type) : type;
});
}
InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences;
@@ -97965,6 +99195,8 @@ var ts;
case 37 /* PlusToken */:
usageContext.isNumberOrString = true;
break;
+ // case SyntaxKind.ExclamationToken:
+ // no inferences here;
}
}
function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) {
@@ -98230,9 +99462,7 @@ var ts;
var opts = context.program.getCompilerOptions();
var variations = [];
// import Bluebird from "bluebird";
- variations.push(createAction(context, sourceFile, node, ts.createImportDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
@@ -98281,7 +99511,171 @@ var ts;
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
+ var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
+ var fixIdAddInitializer = "addMissingPropertyInitializer";
+ var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start);
+ if (!propertyDeclaration)
+ return;
+ var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
+ var result = [
+ getActionForAddMissingUndefinedType(context, propertyDeclaration),
+ getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter)
+ ];
+ ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter));
+ return result;
+ },
+ fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
+ getAllCodeActions: function (context) {
+ var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options);
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start);
+ if (!propertyDeclaration)
+ return;
+ switch (context.fixId) {
+ case fixIdAddDefiniteAssignmentAssertions:
+ addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration, newLineCharacter);
+ break;
+ case fixIdAddUndefinedType:
+ addUndefinedType(changes, diag.file, propertyDeclaration);
+ break;
+ case fixIdAddInitializer:
+ var checker = context.program.getTypeChecker();
+ var initializer = getInitializer(checker, propertyDeclaration);
+ if (!initializer)
+ return;
+ addInitializer(changes, diag.file, propertyDeclaration, initializer, newLineCharacter);
+ break;
+ default:
+ ts.Debug.fail(JSON.stringify(context.fixId));
+ }
+ });
+ },
+ });
+ function getPropertyDeclaration(sourceFile, pos) {
+ var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined;
+ }
+ function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter) {
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_definite_assignment_assertion_to_property_0), [propertyDeclaration.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration, newLineCharacter); });
+ return { description: description, changes: changes, fixId: fixIdAddDefiniteAssignmentAssertions };
+ }
+ function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, newLineCharacter) {
+ var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer);
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter });
+ }
+ function getActionForAddMissingUndefinedType(context, propertyDeclaration) {
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_undefined_type_to_property_0), [propertyDeclaration.name.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); });
+ return { description: description, changes: changes, fixId: fixIdAddUndefinedType };
+ }
+ function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
+ var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */);
+ var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode];
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types));
+ }
+ function getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter) {
+ var checker = context.program.getTypeChecker();
+ var initializer = getInitializer(checker, propertyDeclaration);
+ if (!initializer)
+ return undefined;
+ var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_initializer_to_property_0), [propertyDeclaration.name.getText()]);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer, newLineCharacter); });
+ return { description: description, changes: changes, fixId: fixIdAddInitializer };
+ }
+ function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer, newLineCharacter) {
+ var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer);
+ changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter });
+ }
+ function getInitializer(checker, propertyDeclaration) {
+ return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type));
+ }
+ function getDefaultValueFromType(checker, type) {
+ if (type.flags & 2 /* String */) {
+ return ts.createLiteral("");
+ }
+ else if (type.flags & 4 /* Number */) {
+ return ts.createNumericLiteral("0");
+ }
+ else if (type.flags & 8 /* Boolean */) {
+ return ts.createFalse();
+ }
+ else if (type.flags & 224 /* Literal */) {
+ return ts.createLiteral(type.value);
+ }
+ else if (type.flags & 131072 /* Union */) {
+ return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); });
+ }
+ else if (ts.getObjectFlags(type) & 1 /* Class */) {
+ var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
+ if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */))
+ return undefined;
+ var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; });
+ if (constructorDeclaration && constructorDeclaration.parameters.length)
+ return undefined;
+ return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
+ }
+ return undefined;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "useDefaultImport";
+ var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, start = context.span.start;
+ var info = getInfo(sourceFile, start);
+ if (!info)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
+ return [{ description: description, changes: changes, fixId: fixId }];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var info = getInfo(diag.file, diag.start);
+ if (info)
+ doChange(changes, diag.file, info);
+ }); },
+ });
+ function getInfo(sourceFile, pos) {
+ var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ if (!ts.isIdentifier(name))
+ return undefined; // bad input
+ var parent = name.parent;
+ if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) {
+ return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression };
+ }
+ else if (ts.isNamespaceImport(parent)) {
+ var importNode = parent.parent.parent;
+ return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier };
+ }
+ }
+ function doChange(changes, sourceFile, info) {
+ changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
///
+///
+///
+///
///
///
///
@@ -98300,960 +99694,8 @@ var ts;
///
///
///
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var annotateWithTypeFromJSDoc;
- (function (annotateWithTypeFromJSDoc) {
- var refactorName = "Annotate with type from JSDoc";
- var actionName = "annotate";
- var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (ts.isInJavaScriptFile(context.file)) {
- return undefined;
- }
- var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false);
- if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) {
- return [{
- name: refactorName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName
- }
- ]
- }];
- }
- }
- function hasUsableJSDoc(decl) {
- if (!decl) {
- return false;
- }
- if (ts.isFunctionLikeDeclaration(decl)) {
- return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl));
- }
- return !decl.type && !!ts.getJSDocType(decl);
- }
- function getEditsForAction(context, action) {
- if (actionName !== action) {
- return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action);
- }
- var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false);
- var decl = ts.findAncestor(node, isDeclarationWithType);
- if (!decl || decl.type) {
- return undefined;
- }
- var jsdocType = ts.getJSDocType(decl);
- var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }));
- if (isFunctionWithJSDoc || jsdocType && decl.kind === 148 /* Parameter */) {
- return getEditsForFunctionAnnotation(context);
- }
- else if (jsdocType) {
- return getEditsForAnnotation(context);
- }
- else {
- ts.Debug.assert(!!refactor, "No applicable refactor found.");
- }
- }
- function getEditsForAnnotation(context) {
- var sourceFile = context.file;
- var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false);
- var decl = ts.findAncestor(token, isDeclarationWithType);
- var jsdocType = ts.getJSDocType(decl);
- if (!decl || !jsdocType || decl.type) {
- return ts.Debug.fail("!decl || !jsdocType || decl.type: !" + decl + " || !" + jsdocType + " || " + decl.type);
- }
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var declarationWithType = addType(decl, transformJSDocType(jsdocType));
- ts.suppressLeadingAndTrailingTrivia(declarationWithType);
- changeTracker.replaceNode(sourceFile, decl, declarationWithType, ts.textChanges.useNonAdjustedPositions);
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined
- };
- }
- function getEditsForFunctionAnnotation(context) {
- var sourceFile = context.file;
- var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false);
- var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration);
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var functionWithType = addTypesToFunctionLike(decl);
- ts.suppressLeadingAndTrailingTrivia(functionWithType);
- changeTracker.replaceNode(sourceFile, decl, functionWithType, ts.textChanges.useNonAdjustedPositions);
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined
- };
- }
- function isDeclarationWithType(node) {
- return ts.isFunctionLikeDeclaration(node) ||
- node.kind === 230 /* VariableDeclaration */ ||
- node.kind === 148 /* Parameter */ ||
- node.kind === 150 /* PropertySignature */ ||
- node.kind === 151 /* PropertyDeclaration */;
- }
- function addTypesToFunctionLike(decl) {
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, /*checkJSDoc*/ true);
- var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, /*checkJSDoc*/ true)), p.initializer); });
- var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, /*checkJSDoc*/ true));
- switch (decl.kind) {
- case 232 /* FunctionDeclaration */:
- return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
- case 154 /* Constructor */:
- return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body);
- case 190 /* FunctionExpression */:
- return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body);
- case 191 /* ArrowFunction */:
- return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body);
- case 153 /* MethodDeclaration */:
- return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body);
- case 155 /* GetAccessor */:
- return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body);
- case 156 /* SetAccessor */:
- return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body);
- default:
- return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind);
- }
- }
- function addType(decl, jsdocType) {
- switch (decl.kind) {
- case 230 /* VariableDeclaration */:
- return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer);
- case 150 /* PropertySignature */:
- return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
- case 151 /* PropertyDeclaration */:
- return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer);
- default:
- return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind);
- }
- }
- function transformJSDocType(node) {
- if (node === undefined) {
- return undefined;
- }
- switch (node.kind) {
- case 275 /* JSDocAllType */:
- case 276 /* JSDocUnknownType */:
- return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 279 /* JSDocOptionalType */:
- return transformJSDocOptionalType(node);
- case 278 /* JSDocNonNullableType */:
- return transformJSDocType(node.type);
- case 277 /* JSDocNullableType */:
- return transformJSDocNullableType(node);
- case 281 /* JSDocVariadicType */:
- return transformJSDocVariadicType(node);
- case 280 /* JSDocFunctionType */:
- return transformJSDocFunctionType(node);
- case 148 /* Parameter */:
- return transformJSDocParameter(node);
- case 161 /* TypeReference */:
- return transformJSDocTypeReference(node);
- default:
- var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined);
- ts.setEmitFlags(visited, 1 /* SingleLine */);
- return visited;
- }
- }
- function transformJSDocOptionalType(node) {
- return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
- }
- function transformJSDocNullableType(node) {
- return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
- }
- function transformJSDocVariadicType(node) {
- return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
- }
- function transformJSDocFunctionType(node) {
- var parameters = node.parameters && node.parameters.map(transformJSDocType);
- return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type);
- }
- function transformJSDocParameter(node) {
- var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 281 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
- var name = node.name || (isRest ? "rest" : "arg" + index);
- var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
- return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
- }
- function transformJSDocTypeReference(node) {
- var name = node.typeName;
- var args = node.typeArguments;
- if (ts.isIdentifier(node.typeName)) {
- if (ts.isJSDocIndexSignature(node)) {
- return transformJSDocIndexSignature(node);
- }
- var text = node.typeName.text;
- switch (node.typeName.text) {
- case "String":
- case "Boolean":
- case "Object":
- case "Number":
- text = text.toLowerCase();
- break;
- case "array":
- case "date":
- case "promise":
- text = text[0].toUpperCase() + text.slice(1);
- break;
- }
- name = ts.createIdentifier(text);
- if ((text === "Array" || text === "Promise") && !node.typeArguments) {
- args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
- }
- else {
- args = ts.visitNodes(node.typeArguments, transformJSDocType);
- }
- }
- return ts.createTypeReferenceNode(name, args);
- }
- function transformJSDocIndexSignature(node) {
- var index = ts.createParameter(
- /*decorators*/ undefined,
- /*modifiers*/ undefined,
- /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s",
- /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []),
- /*initializer*/ undefined);
- var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
- ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
- return indexSignature;
- }
- })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var convertFunctionToES6Class;
- (function (convertFunctionToES6Class) {
- var refactorName = "Convert to ES2015 class";
- var actionName = "convert";
- var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message;
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (!ts.isInJavaScriptFile(context.file)) {
- return undefined;
- }
- var symbol = getConstructorSymbol(context);
- if (!symbol) {
- return undefined;
- }
- if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) {
- symbol = symbol.valueDeclaration.initializer.symbol;
- }
- if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) {
- return [
- {
- name: refactorName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName
- }
- ]
- }
- ];
- }
- }
- function getEditsForAction(context, action) {
- // Somehow wrong action got invoked?
- if (actionName !== action) {
- return undefined;
- }
- var sourceFile = context.file;
- var ctorSymbol = getConstructorSymbol(context);
- var deletedNodes = [];
- var deletes = [];
- if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
- return undefined;
- }
- var ctorDeclaration = ctorSymbol.valueDeclaration;
- var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var precedingNode;
- var newClassDeclaration;
- switch (ctorDeclaration.kind) {
- case 232 /* FunctionDeclaration */:
- precedingNode = ctorDeclaration;
- deleteNode(ctorDeclaration);
- newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
- break;
- case 230 /* VariableDeclaration */:
- precedingNode = ctorDeclaration.parent.parent;
- if (ctorDeclaration.parent.declarations.length === 1) {
- deleteNode(precedingNode);
- }
- else {
- deleteNode(ctorDeclaration, /*inList*/ true);
- }
- newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
- break;
- }
- if (!newClassDeclaration) {
- return undefined;
- }
- // Because the preceding node could be touched, we need to insert nodes before delete nodes.
- changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
- for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) {
- var deleteCallback = deletes_1[_i];
- deleteCallback();
- }
- return {
- edits: changeTracker.getChanges(),
- renameFilename: undefined,
- renameLocation: undefined,
- };
- function deleteNode(node, inList) {
- if (inList === void 0) { inList = false; }
- if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) {
- // Parent node has already been deleted; do nothing
- return;
- }
- deletedNodes.push(node);
- if (inList) {
- deletes.push(function () { return changeTracker.deleteNodeInList(sourceFile, node); });
- }
- else {
- deletes.push(function () { return changeTracker.deleteNode(sourceFile, node); });
- }
- }
- function createClassElementsFromSymbol(symbol) {
- var memberElements = [];
- // all instance members are stored in the "member" array of symbol
- if (symbol.members) {
- symbol.members.forEach(function (member) {
- var memberElement = createClassElement(member, /*modifiers*/ undefined);
- if (memberElement) {
- memberElements.push(memberElement);
- }
- });
- }
- // all static members are stored in the "exports" array of symbol
- if (symbol.exports) {
- symbol.exports.forEach(function (member) {
- var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]);
- if (memberElement) {
- memberElements.push(memberElement);
- }
- });
- }
- return memberElements;
- function shouldConvertDeclaration(_target, source) {
- // Right now the only thing we can convert are function expressions - other values shouldn't get
- // transformed. We can update this once ES public class properties are available.
- return ts.isFunctionLike(source);
- }
- function createClassElement(symbol, modifiers) {
- // both properties and methods are bound as property symbols
- if (!(symbol.flags & 4 /* Property */)) {
- return;
- }
- var memberDeclaration = symbol.valueDeclaration;
- var assignmentBinaryExpression = memberDeclaration.parent;
- if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
- return;
- }
- // 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 === 214 /* ExpressionStatement */
- ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
- deleteNode(nodeToDelete);
- if (!assignmentBinaryExpression.right) {
- return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
- /*type*/ undefined, /*initializer*/ undefined);
- }
- switch (assignmentBinaryExpression.right.kind) {
- case 190 /* FunctionExpression */: {
- var functionExpression = assignmentBinaryExpression.right;
- var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */));
- var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
- /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- copyComments(assignmentBinaryExpression, method);
- return method;
- }
- case 191 /* ArrowFunction */: {
- var arrowFunction = assignmentBinaryExpression.right;
- var arrowFunctionBody = arrowFunction.body;
- var bodyBlock = void 0;
- // case 1: () => { return [1,2,3] }
- if (arrowFunctionBody.kind === 211 /* Block */) {
- bodyBlock = arrowFunctionBody;
- }
- else {
- bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
- }
- var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */));
- var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
- /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- copyComments(assignmentBinaryExpression, method);
- return method;
- }
- default: {
- // Don't try to declare members in JavaScript files
- if (ts.isSourceFileJavaScript(sourceFile)) {
- return;
- }
- var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
- /*type*/ undefined, assignmentBinaryExpression.right);
- copyComments(assignmentBinaryExpression.parent, prop);
- return prop;
- }
- }
- }
- }
- function copyComments(sourceNode, targetNode) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
- if (kind === 3 /* MultiLineCommentTrivia */) {
- // Remove leading /*
- pos += 2;
- // Remove trailing */
- end -= 2;
- }
- else {
- // Remove leading //
- pos += 2;
- }
- ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl);
- });
- }
- function createClassFromVariableDeclaration(node) {
- var initializer = node.initializer;
- if (!initializer || initializer.kind !== 190 /* FunctionExpression */) {
- return undefined;
- }
- if (node.name.kind !== 71 /* Identifier */) {
- return undefined;
- }
- var memberElements = createClassElementsFromSymbol(initializer.symbol);
- if (initializer.body) {
- memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
- }
- var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */);
- var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
- /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
- // Don't call copyComments here because we'll already leave them in place
- return cls;
- }
- function createClassFromFunctionDeclaration(node) {
- var memberElements = createClassElementsFromSymbol(ctorSymbol);
- if (node.body) {
- memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
- }
- var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */);
- var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name,
- /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
- // Don't call copyComments here because we'll already leave them in place
- return cls;
- }
- function getModifierKindFromSource(source, kind) {
- return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
- }
- }
- function getConstructorSymbol(_a) {
- var startPosition = _a.startPosition, file = _a.file, program = _a.program;
- var checker = program.getTypeChecker();
- var token = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- return checker.getSymbolAtLocation(token);
- }
- })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var actionName = "Convert to ES6 module";
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module);
- refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- var file = context.file, startPosition = context.startPosition;
- if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) {
- return undefined;
- }
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- return !isAtTriggerLocation(file, node) ? undefined : [
- {
- name: actionName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function isAtTriggerLocation(sourceFile, node, onSecondTry) {
- if (onSecondTry === void 0) { onSecondTry = false; }
- switch (node.kind) {
- case 185 /* CallExpression */:
- return isAtTopLevelRequire(node);
- case 183 /* PropertyAccessExpression */:
- return ts.isExportsOrModuleExportsOrAlias(sourceFile, node)
- || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression);
- case 231 /* VariableDeclarationList */:
- return isVariableDeclarationTriggerLocation(ts.firstOrUndefined(node.declarations));
- case 230 /* VariableDeclaration */:
- return isVariableDeclarationTriggerLocation(node);
- default:
- return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node)
- || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true);
- }
- function isVariableDeclarationTriggerLocation(decl) {
- return !!decl && !!decl.initializer && ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer);
- }
- }
- function isAtTopLevelRequire(call) {
- if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) {
- return false;
- }
- var propAccess = call.parent;
- var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess;
- if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) {
- return true;
- }
- if (!ts.isVariableDeclaration(varDecl)) {
- return false;
- }
- var varDeclList = varDecl.parent;
- if (varDeclList.kind !== 231 /* VariableDeclarationList */) {
- return false;
- }
- var varStatement = varDeclList.parent;
- return varStatement.kind === 212 /* VariableStatement */ && varStatement.parent.kind === 272 /* SourceFile */;
- }
- function getEditsForAction(context, _actionName) {
- ts.Debug.assertEqual(actionName, _actionName);
- var file = context.file, program = context.program;
- ts.Debug.assert(ts.isSourceFileJavaScript(file));
- var edits = ts.textChanges.ChangeTracker.with(context, function (changes) {
- var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target);
- if (moduleExportsChangedToDefault) {
- for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
- var importingFile = _a[_i];
- fixImportOfModuleExports(importingFile, file, changes);
- }
- }
- });
- return { edits: edits, renameFilename: undefined, renameLocation: undefined };
- }
- function fixImportOfModuleExports(importingFile, exportingFile, changes) {
- for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
- var moduleSpecifier = _a[_i];
- var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
- if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
- continue;
- }
- var parent = moduleSpecifier.parent;
- switch (parent.kind) {
- case 252 /* ExternalModuleReference */: {
- var importEq = parent.parent;
- changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text));
- break;
- }
- case 185 /* CallExpression */: {
- var call = parent;
- if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) {
- changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default"));
- }
- break;
- }
- }
- }
- }
- /** @returns Whether we converted a `module.exports =` to a default export. */
- function convertFileToEs6Module(sourceFile, checker, changes, target) {
- var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
- var exports = collectExportRenames(sourceFile, checker, identifiers);
- convertExportsAccesses(sourceFile, exports, changes);
- var moduleExportsChangedToDefault = false;
- for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
- var statement = _a[_i];
- var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports);
- moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
- }
- return moduleExportsChangedToDefault;
- }
- function collectExportRenames(sourceFile, checker, identifiers) {
- var res = ts.createMap();
- forEachExportReference(sourceFile, function (node) {
- var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
- if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
- || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) {
- // Unconditionally add an underscore in case `text` is a keyword.
- res.set(text, makeUniqueName("_" + text, identifiers));
- }
- });
- return res;
- }
- function convertExportsAccesses(sourceFile, exports, changes) {
- forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
- if (isAssignmentLhs) {
- return;
- }
- var text = node.name.text;
- changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
- });
- }
- function forEachExportReference(sourceFile, cb) {
- sourceFile.forEachChild(function recur(node) {
- if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
- var parent = node.parent;
- cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */);
- }
- node.forEachChild(recur);
- });
- }
- function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) {
- switch (statement.kind) {
- case 212 /* VariableStatement */:
- convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target);
- return false;
- case 214 /* ExpressionStatement */: {
- var expression = statement.expression;
- switch (expression.kind) {
- case 185 /* CallExpression */: {
- if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) {
- // For side-effecting require() call, just make a side-effecting import.
- changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text));
- }
- return false;
- }
- case 198 /* BinaryExpression */: {
- var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
- return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports);
- }
- }
- }
- // falls through
- default:
- return false;
- }
- }
- function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) {
- var declarationList = statement.declarationList;
- var foundImport = false;
- var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
- var name = decl.name, initializer = decl.initializer;
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
- // `const alias = module.exports;` can be removed.
- foundImport = true;
- return [];
- }
- if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) {
- foundImport = true;
- return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target);
- }
- else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) {
- foundImport = true;
- return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers);
- }
- else {
- // Move it out to its own variable statement.
- return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
- }
- });
- if (foundImport) {
- // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- }
- }
- /** Converts `const name = require("moduleSpecifier").propertyName` */
- function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) {
- switch (name.kind) {
- case 178 /* ObjectBindingPattern */:
- case 179 /* ArrayBindingPattern */: {
- // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
- var tmp = makeUniqueName(propertyName, identifiers);
- return [
- makeSingleImport(tmp, propertyName, moduleSpecifier),
- makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
- ];
- }
- case 71 /* Identifier */:
- // `const a = require("b").c` --> `import { c as a } from "./b";
- return [makeSingleImport(name.text, propertyName, moduleSpecifier)];
- default:
- ts.Debug.assertNever(name);
- }
- }
- function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) {
- if (!ts.isPropertyAccessExpression(left)) {
- return false;
- }
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
- if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
- // `const alias = module.exports;` or `module.exports = alias;` can be removed.
- changes.deleteNode(sourceFile, statement);
- }
- else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
- }
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- return changedToDefaultExport;
- }
- }
- else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
- convertNamedExport(sourceFile, statement, left.name, right, changes, exports);
- }
- return false;
- var _a;
- }
- /**
- * Convert `module.exports = { ... }` to individual exports..
- * We can't always do this if the module has interesting members -- then it will be a default export instead.
- */
- function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
- switch (prop.kind) {
- case 155 /* GetAccessor */:
- case 156 /* SetAccessor */:
- // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
- case 269 /* ShorthandPropertyAssignment */:
- case 270 /* SpreadAssignment */:
- return undefined;
- case 268 /* PropertyAssignment */:
- return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer);
- case 153 /* MethodDeclaration */:
- return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop);
- default:
- ts.Debug.assertNever(prop);
- }
- });
- }
- function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) {
- // If "originalKeywordKind" was set, this is e.g. `exports.
- var text = propertyName.text;
- var rename = exports.get(text);
- if (rename !== undefined) {
- /*
- const _class = 0;
- export { _class as class };
- */
- var newNodes = [
- makeConst(/*modifiers*/ undefined, rename, right),
- makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
- ];
- changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
- }
- else {
- changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true });
- }
- }
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
- switch (exported.kind) {
- case 190 /* FunctionExpression */:
- case 191 /* ArrowFunction */: {
- // `module.exports = function f() {}` --> `export default function f() {}`
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 203 /* ClassExpression */: {
- // `module.exports = class C {}` --> `export default class C {}`
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 185 /* CallExpression */:
- if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) {
- return convertReExportAll(exported.arguments[0], checker);
- }
- // falls through
- default:
- // `module.exports = 0;` --> `export default 0;`
- return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
- }
- }
- function convertReExportAll(reExported, checker) {
- // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
- var moduleSpecifier = reExported.text;
- var moduleSymbol = checker.getSymbolAtLocation(reExported);
- var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
- return exports.has("export=")
- ? [[reExportDefault(moduleSpecifier)], true]
- : !exports.has("default")
- ? [[reExportStar(moduleSpecifier)], false]
- // If there's some non-default export, must include both `export *` and `export default`.
- : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
- }
- function reExportStar(moduleSpecifier) {
- return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
- }
- function reExportDefault(moduleSpecifier) {
- return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
- }
- function convertExportsDotXEquals(name, exported) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */)];
- switch (exported.kind) {
- case 190 /* FunctionExpression */: {
- var expressionName = exported.name;
- if (expressionName && expressionName.text !== name) {
- // `exports.f = function g() {}` -> `export const f = function g() {}`
- return exportConst();
- }
- }
- // falls through
- case 191 /* ArrowFunction */:
- // `exports.f = function() {}` --> `export function f() {}`
- return functionExpressionToDeclaration(name, modifiers, exported);
- case 203 /* ClassExpression */:
- // `exports.C = class {}` --> `export class C {}`
- return classExpressionToDeclaration(name, modifiers, exported);
- default:
- return exportConst();
- }
- function exportConst() {
- // `exports.x = 0;` --> `export const x = 0;`
- return makeConst(modifiers, ts.createIdentifier(name), exported);
- }
- }
- /**
- * Converts `const <> = require("x");`.
- * Returns nodes that will replace the variable declaration for the commonjs import.
- * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
- */
- function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) {
- switch (name.kind) {
- case 178 /* 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
- : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
- });
- if (importSpecifiers) {
- return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
- }
- }
- // falls through -- object destructuring has an interesting pattern and must be a variable declaration
- case 179 /* ArrayBindingPattern */: {
- /*
- import x from "x";
- const [a, b, c] = x;
- */
- var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers);
- return [
- makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
- makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
- ];
- }
- case 71 /* Identifier */:
- return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers);
- default:
- ts.Debug.assertNever(name);
- }
- }
- /**
- * Convert `import x = require("x").`
- * Also converts uses like `x.y()` to `y()` and uses a named import.
- */
- function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) {
- var nameSymbol = checker.getSymbolAtLocation(name);
- // Maps from module property name to name actually used. (The same if there isn't shadowing.)
- var namedBindingsNames = ts.createMap();
- // True if there is some non-property use like `x()` or `f(x)`.
- var needDefaultImport = false;
- for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
- var use = _a[_i];
- if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
- // This was a use of a different symbol with the same name, due to shadowing. Ignore.
- continue;
- }
- var parent = use.parent;
- if (ts.isPropertyAccessExpression(parent)) {
- var expression = parent.expression, propertyName = parent.name.text;
- ts.Debug.assert(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);
- }
- changes.replaceNode(file, parent, ts.createIdentifier(idName));
- }
- else {
- needDefaultImport = true;
- }
- }
- var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
- var propertyName = _a[0], idName = _a[1];
- return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
- }));
- if (!namedBindings) {
- // If it was unused, ensure that we at least import *something*.
- needDefaultImport = true;
- }
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
- }
- // Identifiers helpers
- function makeUniqueName(name, identifiers) {
- while (identifiers.original.has(name) || identifiers.additional.has(name)) {
- name = "_" + name;
- }
- identifiers.additional.set(name, true);
- return name;
- }
- function collectFreeIdentifiers(file) {
- var map = ts.createMultiMap();
- file.forEachChild(function recur(node) {
- if (ts.isIdentifier(node) && isFreeIdentifier(node)) {
- map.add(node.text, node);
- }
- node.forEachChild(recur);
- });
- return map;
- }
- function isFreeIdentifier(node) {
- var parent = node.parent;
- switch (parent.kind) {
- case 183 /* PropertyAccessExpression */:
- return parent.name !== node;
- case 180 /* BindingElement */:
- return parent.propertyName !== node;
- default:
- return true;
- }
- }
- // Node helpers
- function functionExpressionToDeclaration(name, additionalModifiers, fn) {
- return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
- ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
- }
- function classExpressionToDeclaration(name, additionalModifiers, cls) {
- return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
- ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
- }
- function makeSingleImport(localName, propertyName, moduleSpecifier) {
- return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
- : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
- }
- function makeImport(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier));
- }
- function makeImportSpecifier(propertyName, name) {
- return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
- }
- function makeConst(modifiers, name, init) {
- return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
- }
- function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
- return ts.createExportDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
- }
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
+///
+///
///
///
/* @internal */
@@ -99478,7 +99920,7 @@ var ts;
}
else if (ts.isVariableStatement(node)) {
var numInitializers = 0;
- var lastInitializer = undefined;
+ var lastInitializer = void 0;
for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (declaration.initializer) {
@@ -99595,7 +100037,7 @@ var ts;
switch (node.kind) {
case 232 /* FunctionDeclaration */:
case 233 /* ClassDeclaration */:
- if (node.parent.kind === 272 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) {
+ if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
// You cannot extract global declarations
(errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
}
@@ -99875,12 +100317,12 @@ var ts;
var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text);
var isJS = ts.isInJavaScriptFile(scope);
var functionName = ts.createIdentifier(functionNameText);
- var returnType = undefined;
+ var returnType;
var parameters = [];
var callArguments = [];
var writes;
usagesInScope.forEach(function (usage, name) {
- var typeNode = undefined;
+ var typeNode;
if (!isJS) {
var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
// Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
@@ -100167,7 +100609,7 @@ var ts;
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function getContainingVariableDeclarationIfInList(node, scope) {
- var prevNode = undefined;
+ var prevNode;
while (node !== undefined && node !== scope) {
if (ts.isVariableDeclaration(node) &&
node.initializer === prevNode &&
@@ -100192,16 +100634,16 @@ var ts;
ts.Debug.assert(fileName === renameFilename);
for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) {
var change = textChanges_3[_b];
- var span_15 = change.span, newText = change.newText;
+ var span_14 = change.span, newText = change.newText;
var index = newText.indexOf(functionNameText);
if (index !== -1) {
- lastPos = span_15.start + delta + index;
+ lastPos = span_14.start + delta + index;
// If the reference comes first, return immediately.
if (!isDeclaredBeforeUse) {
return lastPos;
}
}
- delta += newText.length - span_15.length;
+ delta += newText.length - span_14.length;
}
}
// If the declaration comes first, return the position of the last occurrence.
@@ -100210,7 +100652,7 @@ var ts;
return lastPos;
}
function getFirstDeclaration(type) {
- var firstDeclaration = undefined;
+ var firstDeclaration;
var symbol = type.symbol;
if (symbol && symbol.declarations) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
@@ -100332,7 +100774,7 @@ var ts;
function getNodeToInsertPropertyBefore(maxPos, scope) {
var members = scope.members;
ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one.
- var prevMember = undefined;
+ var prevMember;
var allProperties = true;
for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
var member = members_6[_i];
@@ -100354,7 +100796,7 @@ var ts;
}
function getNodeToInsertConstantBefore(node, scope) {
ts.Debug.assert(!ts.isClassLike(scope));
- var prevScope = undefined;
+ var prevScope;
for (var curr = node; curr !== scope; curr = curr.parent) {
if (isScope(curr)) {
prevScope = curr;
@@ -100362,7 +100804,7 @@ var ts;
}
for (var curr = (prevScope || node).parent;; curr = curr.parent) {
if (isBlockLike(curr)) {
- var prevStatement = undefined;
+ var prevStatement = void 0;
for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) {
var statement = _a[_i];
if (statement.pos > node.pos) {
@@ -100427,13 +100869,13 @@ var ts;
var visibleDeclarationsInExtractedRange = [];
var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID
var exposedVariableDeclarations = [];
- var firstExposedNonVariableDeclaration = undefined;
+ var firstExposedNonVariableDeclaration;
var expression = !isReadonlyArray(targetRange.range)
? targetRange.range
: targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0])
? targetRange.range[0].expression
: undefined;
- var expressionDiagnostic = undefined;
+ var expressionDiagnostic;
if (expression === undefined) {
var statements = targetRange.range;
var start = ts.first(statements).getStart();
@@ -100511,7 +100953,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_10 = function (i) {
+ var _loop_11 = 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
@@ -100521,7 +100963,7 @@ var ts;
constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
}
var hasWrite = false;
- var readonlyClassPropertyWrite = undefined;
+ var readonlyClassPropertyWrite;
usagesPerScope[i].usages.forEach(function (value) {
if (value.usage === 2 /* Write */) {
hasWrite = true;
@@ -100551,7 +100993,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_10(i);
+ _loop_11(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function hasTypeParameters(node) {
@@ -100819,165 +101261,7 @@ var ts;
})(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var installTypesForPackage;
- (function (installTypesForPackage) {
- var refactorName = "Install missing types package";
- var actionName = "install";
- var description = "Install missing types package";
- refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) {
- // Then it will be available via `fixCannotFindModule`.
- return undefined;
- }
- var action = getAction(context);
- return action && [
- {
- name: refactorName,
- description: description,
- actions: [
- {
- description: action.description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function getEditsForAction(context, _actionName) {
- ts.Debug.assertEqual(actionName, _actionName);
- var action = getAction(context); // Should be defined if we said there was an action available.
- return {
- edits: [],
- renameFilename: undefined,
- renameLocation: undefined,
- commands: action.commands,
- };
- }
- function getAction(context) {
- var file = context.file, startPosition = context.startPosition;
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- if (!ts.isStringLiteral(node) || !isModuleIdentifier(node)) {
- return undefined;
- }
- var resolvedTo = ts.getResolvedModule(file, node.text);
- // Still offer to install types if it resolved to e.g. a ".js" file.
- // `tryGetCodeActionForInstallPackageTypes` will verify that we're looking for a valid package name,
- // so the fix won't trigger for imports of ".js" files that couldn't be better replaced by typings.
- if (resolvedTo && ts.extensionIsTypeScript(resolvedTo.extension)) {
- return undefined;
- }
- return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, file.fileName, node.text);
- }
- function isModuleIdentifier(node) {
- switch (node.parent.kind) {
- case 242 /* ImportDeclaration */:
- case 252 /* ExternalModuleReference */:
- return true;
- default:
- return false;
- }
- }
- })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var refactor;
- (function (refactor) {
- var installTypesForPackage;
- (function (installTypesForPackage) {
- var actionName = "Convert to default import";
- var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import);
- refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
- function getAvailableActions(context) {
- var file = context.file, startPosition = context.startPosition, program = context.program;
- if (!ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
- return undefined;
- }
- var importInfo = getConvertibleImportAtPosition(file, startPosition);
- if (!importInfo) {
- return undefined;
- }
- var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
- if (!(resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) {
- return undefined;
- }
- return [
- {
- name: actionName,
- description: description,
- actions: [
- {
- description: description,
- name: actionName,
- },
- ],
- },
- ];
- }
- function getEditsForAction(context, _actionName) {
- var file = context.file, startPosition = context.startPosition;
- ts.Debug.assertEqual(actionName, _actionName);
- var importInfo = getConvertibleImportAtPosition(file, startPosition);
- if (!importInfo) {
- return undefined;
- }
- var importStatement = importInfo.importStatement, name = importInfo.name, moduleSpecifier = importInfo.moduleSpecifier;
- var newImportClause = ts.createImportClause(name, /*namedBindings*/ undefined);
- var newImportStatement = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newImportClause, moduleSpecifier);
- return {
- edits: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, importStatement, newImportStatement); }),
- renameFilename: undefined,
- renameLocation: undefined,
- };
- }
- function getConvertibleImportAtPosition(file, startPosition) {
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
- while (true) {
- switch (node.kind) {
- case 241 /* ImportEqualsDeclaration */:
- var eq = node;
- var moduleReference = eq.moduleReference;
- return moduleReference.kind === 252 /* ExternalModuleReference */ && ts.isStringLiteral(moduleReference.expression)
- ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression }
- : undefined;
- case 242 /* ImportDeclaration */:
- var d = node;
- var importClause = d.importClause;
- return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(d.moduleSpecifier)
- ? { importStatement: d, name: importClause.namedBindings.name, moduleSpecifier: d.moduleSpecifier }
- : undefined;
- // For known child node kinds of convertible imports, try again with parent node.
- case 244 /* NamespaceImport */:
- case 252 /* ExternalModuleReference */:
- case 91 /* ImportKeyword */:
- case 71 /* Identifier */:
- case 9 /* StringLiteral */:
- case 39 /* AsteriskToken */:
- break;
- default:
- return undefined;
- }
- node = node.parent;
- }
- }
- })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {}));
- })(refactor = ts.refactor || (ts.refactor = {}));
-})(ts || (ts = {}));
-///
-///
-///
///
-///
-///
///
///
///
@@ -100999,6 +101283,7 @@ var ts;
///
///
///
+///
///
///
///
@@ -101530,20 +101815,8 @@ var ts;
}
function getDeclarationName(declaration) {
var name = ts.getNameOfDeclaration(declaration);
- if (name) {
- var result_6 = ts.getTextOfIdentifierOrLiteral(name);
- if (result_6 !== undefined) {
- return result_6;
- }
- if (name.kind === 146 /* ComputedPropertyName */) {
- var expr = name.expression;
- if (expr.kind === 183 /* PropertyAccessExpression */) {
- return expr.name.text;
- }
- return ts.getTextOfIdentifierOrLiteral(expr);
- }
- }
- return undefined;
+ return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) :
+ name.kind === 146 /* ComputedPropertyName */ && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined);
}
function visit(node) {
switch (node.kind) {
@@ -102130,6 +102403,10 @@ var ts;
var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
return semanticDiagnostics.concat(declarationDiagnostics);
}
+ function getSuggestionDiagnostics(fileName) {
+ synchronizeHostData();
+ return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program);
+ }
function getCompilerOptionsDiagnostics() {
synchronizeHostData();
return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken));
@@ -102152,9 +102429,7 @@ var ts;
var sourceFile = getValidSourceFile(fileName);
var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (node === sourceFile) {
- return undefined;
- }
- if (ts.isLabelName(node)) {
+ // Avoid giving quickInfo for the sourceFile as a whole.
return undefined;
}
var typeChecker = program.getTypeChecker();
@@ -102163,6 +102438,11 @@ var ts;
// Try getting just type at this position and show
switch (node.kind) {
case 71 /* Identifier */:
+ if (ts.isLabelName(node)) {
+ // Type here will be 'any', avoid displaying this.
+ return undefined;
+ }
+ // falls through
case 183 /* PropertyAccessExpression */:
case 145 /* QualifiedName */:
case 99 /* ThisKeyword */:
@@ -102170,27 +102450,25 @@ var ts;
case 97 /* SuperKeyword */:
// For the identifiers/this/super etc get the type at position
var type = typeChecker.getTypeAtLocation(node);
- if (type) {
- return {
- kind: "" /* unknown */,
- kindModifiers: "" /* none */,
- textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
- displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)),
- documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type.symbol ? type.symbol.getJsDocTags() : undefined
- };
- }
+ return type && {
+ kind: "" /* unknown */,
+ kindModifiers: "" /* none */,
+ textSpan: ts.createTextSpanFromNode(node, sourceFile),
+ displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)),
+ documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined,
+ tags: type.symbol ? type.symbol.getJsDocTags() : undefined
+ };
}
return undefined;
}
- var displayPartsDocumentationsAndKind = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node);
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags;
return {
- kind: displayPartsDocumentationsAndKind.symbolKind,
+ kind: symbolKind,
kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
- textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
- displayParts: displayPartsDocumentationsAndKind.displayParts,
- documentation: displayPartsDocumentationsAndKind.documentation,
- tags: displayPartsDocumentationsAndKind.tags
+ textSpan: ts.createTextSpanFromNode(node, sourceFile),
+ displayParts: displayParts,
+ documentation: documentation,
+ tags: tags,
};
}
function getSymbolAtLocationForQuickInfo(node, checker) {
@@ -102198,11 +102476,9 @@ var ts;
&& ts.isPropertyAssignment(node.parent)
&& node.parent.name === node) {
var type = checker.getContextualType(node.parent.parent);
- if (type) {
- var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node));
- if (property) {
- return property;
- }
+ var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node));
+ if (property) {
+ return property;
}
}
return checker.getSymbolAtLocation(node);
@@ -102465,7 +102741,7 @@ var ts;
ts.Debug.assert(scope.type === "file");
var sourceFile = getValidSourceFile(scope.fileName);
var formatContext = ts.formatting.getFormatContext(formatOptions);
- return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host);
+ return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program);
}
function applyCodeActionCommand(fileName, actionOrUndefined) {
var action = typeof fileName === "string" ? actionOrUndefined : fileName;
@@ -102479,6 +102755,7 @@ var ts;
: Promise.reject("Host does not implement `installPackage`");
default:
ts.Debug.fail();
+ // TODO: Debug.assertNever(action); will only work if there is more than one type.
}
}
function getDocCommentTemplateAtPosition(fileName, position) {
@@ -102562,7 +102839,7 @@ var ts;
if (!ts.isInComment(sourceFile, matchPosition)) {
continue;
}
- var descriptor = undefined;
+ var descriptor = void 0;
for (var i = 0; i < descriptors.length; i++) {
if (matchArray[i + firstDescriptorCaptureIndex]) {
descriptor = descriptors[i];
@@ -102673,6 +102950,7 @@ var ts;
cleanupSemanticCache: cleanupSemanticCache,
getSyntacticDiagnostics: getSyntacticDiagnostics,
getSemanticDiagnostics: getSemanticDiagnostics,
+ getSuggestionDiagnostics: getSuggestionDiagnostics,
getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics,
getSyntacticClassifications: getSyntacticClassifications,
getSemanticClassifications: getSemanticClassifications,
@@ -102790,20 +103068,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_7 = [];
+ var result_6 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072 /* Union */) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_7.push(symbol);
+ result_6.push(symbol);
}
});
- return result_7;
+ return result_6;
}
if (symbol) {
- result_7.push(symbol);
- return result_7;
+ result_6.push(symbol);
+ return result_6;
}
}
return undefined;
@@ -103050,24 +103328,23 @@ var ts;
return textSpan(node);
}
if (node.kind === 198 /* BinaryExpression */) {
- var binaryExpression = node;
+ 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
// [a, b, c] = expression or
// {a, b, c} = expression
- if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) {
- return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left);
+ if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
+ return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left);
}
- if (binaryExpression.operatorToken.kind === 58 /* EqualsToken */ &&
- ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) {
+ if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
// Set breakpoint on assignment expression element of destructuring pattern
// a = expression of
// [a = expression, b, c] = someExpression or
// { a = expression, b, c } = someExpression
return textSpan(node);
}
- if (binaryExpression.operatorToken.kind === 26 /* CommaToken */) {
- return spanInNode(binaryExpression.left);
+ if (operatorToken.kind === 26 /* CommaToken */) {
+ return spanInNode(left);
}
}
if (ts.isExpressionNode(node)) {
@@ -103095,46 +103372,49 @@ var ts;
break;
}
}
- // If this is name of property assignment, set breakpoint in the initializer
- if (node.parent.kind === 268 /* PropertyAssignment */ &&
- node.parent.name === node &&
- !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
- return spanInNode(node.parent.initializer);
- }
- // Breakpoint in type assertion goes to its operand
- if (node.parent.kind === 188 /* TypeAssertionExpression */ && node.parent.type === node) {
- return spanInNextNode(node.parent.type);
- }
- // return type of function go to previous token
- if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
- return spanInPreviousNode(node);
- }
- // initializer of variable/parameter declaration go to previous node
- if ((node.parent.kind === 230 /* VariableDeclaration */ ||
- node.parent.kind === 148 /* Parameter */)) {
- var paramOrVarDecl = node.parent;
- if (paramOrVarDecl.initializer === node ||
- paramOrVarDecl.type === node ||
- ts.isAssignmentOperator(node.kind)) {
- return spanInPreviousNode(node);
+ switch (node.parent.kind) {
+ case 268 /* 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 188 /* TypeAssertionExpression */:
+ // Breakpoint in type assertion goes to its operand
+ if (node.parent.type === node) {
+ return spanInNextNode(node.parent.type);
+ }
+ break;
+ case 230 /* VariableDeclaration */:
+ case 148 /* 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)) {
+ return spanInPreviousNode(node);
+ }
+ break;
}
- }
- if (node.parent.kind === 198 /* BinaryExpression */) {
- var binaryExpression = node.parent;
- if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) &&
- (binaryExpression.right === node ||
- binaryExpression.operatorToken === node)) {
- // If initializer of destructuring assignment move to previous token
- return spanInPreviousNode(node);
+ case 198 /* BinaryExpression */: {
+ var left = node.parent.left;
+ if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
+ // If initializer of destructuring assignment move to previous token
+ return spanInPreviousNode(node);
+ }
+ break;
}
+ default:
+ // return type of function go to previous token
+ if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
+ return spanInPreviousNode(node);
+ }
}
// Default go to parent to set the breakpoint
return spanInNode(node.parent);
}
}
function textSpanFromVariableDeclaration(variableDeclaration) {
- if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ &&
- variableDeclaration.parent.declarations[0] === variableDeclaration) {
+ if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
// First declaration - include let keyword
return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
}
@@ -103159,7 +103439,7 @@ var ts;
variableDeclaration.parent.parent.kind === 220 /* ForOfStatement */) {
return textSpanFromVariableDeclaration(variableDeclaration);
}
- if (variableDeclaration.parent.kind === 231 /* VariableDeclarationList */ &&
+ if (ts.isVariableDeclarationList(variableDeclaration.parent) &&
variableDeclaration.parent.declarations[0] !== variableDeclaration) {
// If we cannot set breakpoint on this declaration, set it on previous one
// Because the variable declaration may be binding pattern and
@@ -103717,8 +103997,7 @@ var ts;
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
length: diagnostic.length,
- /// TODO: no need for the tolowerCase call
- category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(),
+ category: ts.diagnosticCategoryName(diagnostic),
code: diagnostic.code
};
}
@@ -103768,7 +104047,7 @@ var ts;
};
LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) {
var newLine = ts.getNewLineOrDefaultFromHost(this.host);
- return ts.realizeDiagnostics(diagnostics, newLine);
+ return realizeDiagnostics(diagnostics, newLine);
};
LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) {
var _this = this;
@@ -103806,6 +104085,10 @@ var ts;
return _this.realizeDiagnostics(diagnostics);
});
};
+ LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) {
+ var _this = this;
+ return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); });
+ };
LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () {
var _this = this;
return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () {
diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js
index 74ec9b4a722..c98aa369e9e 100644
--- a/lib/typingsInstaller.js
+++ b/lib/typingsInstaller.js
@@ -64,8 +64,15 @@ var ts;
(function (DiagnosticCategory) {
DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
- DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message";
+ DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
+ DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
})(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
+ function diagnosticCategoryName(d, lowerCase) {
+ if (lowerCase === void 0) { lowerCase = true; }
+ var name = DiagnosticCategory[d.category];
+ return lowerCase ? name.toLowerCase() : name;
+ }
+ ts.diagnosticCategoryName = diagnosticCategoryName;
var ModuleResolutionKind;
(function (ModuleResolutionKind) {
ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
@@ -81,6 +88,37 @@ var ts;
ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext";
})(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
+ function _contextuallyTypePragmas(args) {
+ return args;
+ }
+ ts.commentPragmas = _contextuallyTypePragmas({
+ "reference": {
+ args: [
+ { name: "types", optional: true, captureSpan: true },
+ { name: "path", optional: true, captureSpan: true },
+ { name: "no-default-lib", optional: true }
+ ],
+ kind: 1
+ },
+ "amd-dependency": {
+ args: [{ name: "path" }, { name: "name", optional: true }],
+ kind: 1
+ },
+ "amd-module": {
+ args: [{ name: "name" }],
+ kind: 1
+ },
+ "ts-check": {
+ kind: 2
+ },
+ "ts-nocheck": {
+ kind: 2
+ },
+ "jsx": {
+ args: [{ name: "factory" }],
+ kind: 4
+ },
+ });
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -142,7 +180,7 @@ var ts;
var ts;
(function (ts) {
ts.versionMajorMinor = "2.8";
- ts.version = ts.versionMajorMinor + ".0-dev";
+ ts.version = ts.versionMajorMinor + ".0";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -1200,19 +1238,21 @@ var ts;
}
ts.equalOwnProperties = equalOwnProperties;
function arrayToMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = createMap();
for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
var value = array_6[_i];
- result.set(makeKey(value), makeValue ? makeValue(value) : value);
+ result.set(makeKey(value), makeValue(value));
}
return result;
}
ts.arrayToMap = arrayToMap;
function arrayToNumericMap(array, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
var result = [];
for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
var value = array_7[_i];
- result[makeKey(value)] = makeValue ? makeValue(value) : value;
+ result[makeKey(value)] = makeValue(value);
}
return result;
}
@@ -1221,6 +1261,20 @@ var ts;
return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; });
}
ts.arrayToSet = arrayToSet;
+ function arrayToMultiMap(values, makeKey, makeValue) {
+ if (makeValue === void 0) { makeValue = identity; }
+ var result = createMultiMap();
+ for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
+ var value = values_1[_i];
+ result.add(makeKey(value), makeValue(value));
+ }
+ return result;
+ }
+ ts.arrayToMultiMap = arrayToMultiMap;
+ function group(values, getGroupId) {
+ return arrayFrom(arrayToMultiMap(values, getGroupId).values());
+ }
+ ts.group = group;
function cloneMap(map) {
var clone = createMap();
copyEntries(map, clone);
@@ -1278,15 +1332,6 @@ var ts;
}
}
}
- function group(values, getGroupId) {
- var groupIdToGroup = createMultiMap();
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- groupIdToGroup.add(getGroupId(value), value);
- }
- return arrayFrom(groupIdToGroup.values());
- }
- ts.group = group;
function isArray(value) {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
@@ -1394,7 +1439,6 @@ var ts;
return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; });
}
ts.formatStringFromArgs = formatStringFromArgs;
- ts.localizedDiagnosticMessages = undefined;
function getLocaleSpecificMessage(message) {
return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
}
@@ -2160,7 +2204,7 @@ var ts;
}
includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive);
var _loop_2 = function (includeBasePath) {
- if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
+ if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
basePaths.push(includeBasePath);
}
};
@@ -2503,7 +2547,7 @@ var ts;
}
ts.matchedText = matchedText;
function findBestPatternMatch(values, getPattern, candidate) {
- var matchedValue = undefined;
+ var matchedValue;
var longestMatchPrefixLength = -1;
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
var v = values_2[_i];
@@ -3616,6 +3660,7 @@ var ts;
Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
+ Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
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}'."),
@@ -3687,7 +3732,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}'."),
- 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.Message, "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."),
+ 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}'."),
Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
@@ -3860,7 +3905,7 @@ var ts;
Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
- Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."),
+ Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
@@ -3904,6 +3949,7 @@ var ts;
Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."),
+ Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."),
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."),
@@ -3983,10 +4029,15 @@ var ts;
JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
+ JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
+ File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
+ This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
+ Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
+ JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
@@ -4027,6 +4078,9 @@ var ts;
Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
+ Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
+ Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
+ Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
};
})(ts || (ts = {}));
var ts;
@@ -4356,8 +4410,7 @@ var ts;
}
ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
function isAmbientModule(node) {
- return node && node.kind === 237 &&
- (node.name.kind === 9 || isGlobalScopeAugmentation(node));
+ return ts.isModuleDeclaration(node) && (node.name.kind === 9 || isGlobalScopeAugmentation(node));
}
ts.isAmbientModule = isAmbientModule;
function isModuleWithStringLiteralName(node) {
@@ -4386,18 +4439,19 @@ var ts;
}
ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
function isExternalModuleAugmentation(node) {
- if (!node || !isAmbientModule(node)) {
- return false;
- }
+ return isAmbientModule(node) && isModuleAugmentationExternal(node);
+ }
+ ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ function isModuleAugmentationExternal(node) {
switch (node.parent.kind) {
case 272:
return ts.isExternalModule(node.parent);
case 238:
- return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
+ return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
}
return false;
}
- ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
function isEffectiveExternalModule(node, compilerOptions) {
return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
}
@@ -5597,14 +5651,7 @@ var ts;
}
ts.isNodeDescendantOf = isNodeDescendantOf;
function isDeclarationName(name) {
- switch (name.kind) {
- case 71:
- case 9:
- case 8:
- return ts.isDeclaration(name.parent) && name.parent.name === name;
- default:
- return false;
- }
+ return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
}
ts.isDeclarationName = isDeclarationName;
function isAnyDeclarationName(name) {
@@ -5717,38 +5764,6 @@ var ts;
return undefined;
}
ts.getAncestor = getAncestor;
- function getFileReferenceFromReferencePath(comment, commentRange) {
- var simpleReferenceRegEx = /^\/\/\/\s*= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
}
ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
function textSpanIntersectsWith(span, start, length) {
- var end = start + length;
- return start <= textSpanEnd(span) && end >= span.start;
+ return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
}
ts.textSpanIntersectsWith = textSpanIntersectsWith;
function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
@@ -7218,12 +7220,9 @@ var ts;
}
ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
function textSpanIntersection(span1, span2) {
- var intersectStart = Math.max(span1.start, span2.start);
- var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
- if (intersectStart <= intersectEnd) {
- return createTextSpanFromBounds(intersectStart, intersectEnd);
- }
- return undefined;
+ var start = Math.max(span1.start, span2.start);
+ var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
+ return start <= end ? createTextSpanFromBounds(start, end) : undefined;
}
ts.textSpanIntersection = textSpanIntersection;
function createTextSpan(start, length) {
@@ -11203,7 +11202,8 @@ var ts;
sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
sourceFile.flags = contextFlags;
nextToken();
- processReferenceComments(sourceFile);
+ processCommentPragmas(sourceFile, sourceText);
+ processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
sourceFile.statements = parseList(0, parseStatement);
ts.Debug.assert(token() === 1);
sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
@@ -11216,6 +11216,9 @@ var ts;
fixupParentReferences(sourceFile);
}
return sourceFile;
+ function reportPragmaDiagnostic(pos, end, diagnostic) {
+ parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
+ }
}
function addJSDocComment(node) {
var comments = ts.getJSDocCommentRanges(node, sourceFile.text);
@@ -13471,8 +13474,8 @@ var ts;
var fullStart = scanner.getStartPos();
parseExpected(27);
if (token() === 29) {
- parseExpected(29);
var node_1 = createNode(258, fullStart);
+ scanJsxText();
return finishNode(node_1);
}
var tagName = parseJsxElementName();
@@ -13511,7 +13514,9 @@ var ts;
}
function parseJsxExpression(inExpressionContext) {
var node = createNode(263);
- parseExpected(17);
+ if (!parseExpected(17)) {
+ return undefined;
+ }
if (token() !== 18) {
node.dotDotDotToken = parseOptionalToken(24);
node.expression = parseAssignmentExpressionOrHigher();
@@ -13935,7 +13940,7 @@ var ts;
parseExpected(88);
var awaitToken = parseOptionalToken(121);
parseExpected(19);
- var initializer = undefined;
+ var initializer;
if (token() !== 25) {
if (token() === 104 || token() === 110 || token() === 76) {
initializer = parseVariableDeclarationList(true);
@@ -14949,84 +14954,6 @@ var ts;
parseSemicolon();
return finishNode(node);
}
- function processReferenceComments(sourceFile) {
- var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText);
- var referencedFiles = [];
- var typeReferenceDirectives = [];
- var amdDependencies = [];
- var amdModuleName;
- var checkJsDirective = undefined;
- while (true) {
- var kind = triviaScanner.scan();
- if (kind !== 2) {
- if (ts.isTrivia(kind)) {
- continue;
- }
- else {
- break;
- }
- }
- var range = {
- kind: triviaScanner.getToken(),
- pos: triviaScanner.getTokenPos(),
- end: triviaScanner.getTextPos(),
- };
- var comment = sourceText.substring(range.pos, range.end);
- var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range);
- if (referencePathMatchResult) {
- var fileReference = referencePathMatchResult.fileReference;
- sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
- var diagnosticMessage = referencePathMatchResult.diagnosticMessage;
- if (fileReference) {
- if (referencePathMatchResult.isTypeReferenceDirective) {
- typeReferenceDirectives.push(fileReference);
- }
- else {
- referencedFiles.push(fileReference);
- }
- }
- if (diagnosticMessage) {
- parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage));
- }
- }
- else {
- var amdModuleNameRegEx = /^\/\/\/\s* context.checkJsDirective.pos) {
+ context.checkJsDirective = {
+ enabled: key === "ts-check",
+ end: entry.range.end,
+ pos: entry.range.pos
+ };
+ }
+ });
+ break;
+ }
+ case "jsx": return;
+ default: ts.Debug.fail("Unhandled pragma kind");
+ }
+ });
+ }
+ ts.processPragmasIntoFields = processPragmasIntoFields;
+ var namedArgRegExCache = ts.createMap();
+ function getNamedArgRegEx(name) {
+ if (namedArgRegExCache.has(name)) {
+ return namedArgRegExCache.get(name);
+ }
+ var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
+ namedArgRegExCache.set(name, result);
+ return result;
+ }
+ var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
+ var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
+ function extractPragmas(pragmas, range, text) {
+ var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text);
+ if (tripleSlash) {
+ var name = tripleSlash[1].toLowerCase();
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & 1)) {
+ return;
+ }
+ if (pragma.args) {
+ var argument = {};
+ for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
+ var arg = _a[_i];
+ var matcher = getNamedArgRegEx(arg.name);
+ var matchResult = matcher.exec(text);
+ if (!matchResult && !arg.optional) {
+ return;
+ }
+ else if (matchResult) {
+ if (arg.captureSpan) {
+ var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
+ argument[arg.name] = {
+ value: matchResult[3],
+ pos: startPos,
+ end: startPos + matchResult[3].length
+ };
+ }
+ else {
+ argument[arg.name] = matchResult[3];
+ }
+ }
+ }
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ }
+ else {
+ pragmas.push({ name: name, args: { arguments: {}, range: range } });
+ }
+ return;
+ }
+ var singleLine = singleLinePragmaRegEx.exec(text);
+ if (singleLine) {
+ return addPragmaForMatch(pragmas, range, 2, singleLine);
+ }
+ var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim;
+ var multiLineMatch;
+ while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
+ addPragmaForMatch(pragmas, range, 4, multiLineMatch);
+ }
+ }
+ function addPragmaForMatch(pragmas, range, kind, match) {
+ if (!match)
+ return;
+ var name = match[1].toLowerCase();
+ var pragma = ts.commentPragmas[name];
+ if (!pragma || !(pragma.kind & kind)) {
+ return;
+ }
+ var args = match[2];
+ var argument = getNamedPragmaArguments(pragma, args);
+ if (argument === "fail")
+ return;
+ pragmas.push({ name: name, args: { arguments: argument, range: range } });
+ return;
+ }
+ function getNamedPragmaArguments(pragma, text) {
+ if (!text)
+ return {};
+ if (!pragma.args)
+ return {};
+ var args = text.split(/\s+/);
+ var argMap = {};
+ for (var i = 0; i < pragma.args.length; i++) {
+ var argument = pragma.args[i];
+ if (!args[i] && !argument.optional) {
+ return "fail";
+ }
+ if (argument.captureSpan) {
+ return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
+ }
+ argMap[argument.name] = args[i];
+ }
+ return argMap;
+ }
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -16031,6 +16152,13 @@ var ts;
category: ts.Diagnostics.Command_line_Options,
description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
},
+ {
+ name: "preserveWatchOutput",
+ type: "boolean",
+ showInSimplifiedHelpView: false,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
+ },
{
name: "watch",
shortName: "w",
@@ -16108,9 +16236,10 @@ var ts;
"es2017.string": "lib.es2017.string.d.ts",
"es2017.intl": "lib.es2017.intl.d.ts",
"es2017.typedarrays": "lib.es2017.typedarrays.d.ts",
+ "es2018.promise": "lib.es2018.promise.d.ts",
+ "es2018.regexp": "lib.es2018.regexp.d.ts",
"esnext.array": "lib.esnext.array.d.ts",
"esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
- "esnext.promise": "lib.esnext.promise.d.ts",
}),
},
showInSimplifiedHelpView: true,
@@ -17956,8 +18085,10 @@ var ts;
}
ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
- var directoryToModuleNameMap = ts.createMap();
- var moduleNameToDirectoryMap = ts.createMap();
+ return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName);
+ }
+ ts.createModuleResolutionCache = createModuleResolutionCache;
+ function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
function getOrCreateCacheForDirectory(directoryName) {
var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
@@ -18023,7 +18154,7 @@ var ts;
}
}
}
- ts.createModuleResolutionCache = createModuleResolutionCache;
+ ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
@@ -18034,7 +18165,7 @@ var ts;
var result = perFolderCache && perFolderCache.get(moduleName);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
}
else {
@@ -18156,7 +18287,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
}
- var matchedPattern = undefined;
+ var matchedPattern;
if (state.compilerOptions.paths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
@@ -18568,6 +18699,7 @@ var ts;
}
return packageName;
}
+ ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage;
function getPackageNameFromAtTypesDirectory(mangledName) {
var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
if (withoutAtTypePrefix !== mangledName) {
@@ -18586,7 +18718,7 @@ var ts;
var result = cache && cache.get(containingDirectory);
if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
}
return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
}
@@ -18901,7 +19033,7 @@ var ts;
case 6:
return "Package name '" + typing + "' contains non URI safe characters";
case 0:
- throw ts.Debug.fail();
+ return ts.Debug.fail();
default:
ts.Debug.assertNever(result);
}
diff --git a/lib/zh-CN/diagnosticMessages.generated.json b/lib/zh-CN/diagnosticMessages.generated.json
index ac797aec838..1fd303748de 100644
--- a/lib/zh-CN/diagnosticMessages.generated.json
+++ b/lib/zh-CN/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "两个取值函数必须都是抽象的或都是非抽象的。",
"Add_0_to_existing_import_declaration_from_1_90015": "将“{0}”从“{1}”添加到现有导入声明",
"Add_async_modifier_to_containing_function_90029": "将异步修饰符添加到包含函数",
+ "Add_definite_assignment_assertion_to_property_0_95020": "向属性“{0}”添加明确的赋值断言",
"Add_index_signature_for_property_0_90017": "为属性“{0}”添加索引签名",
+ "Add_initializer_to_property_0_95019": "向属性“{0}”添加初始值设定项",
"Add_missing_super_call_90001": "添加缺失的 \"super()\" 调用",
"Add_this_to_unresolved_variable_90008": "向未解析的变量添加 \"this.\"",
+ "Add_undefined_type_to_property_0_95018": "向属性“{0}”添加“未定义”类型",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "添加 tsconfig.json 文件有助于组织包含 TypeScript 和 JavaScript 文件的项目。有关详细信息,请访问 https://aka.ms/tsconfig。",
"Additional_Checks_6176": "其他检查",
"Advanced_Options_6178": "高级选项",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "对 ES7 修饰器启用实验支持。",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "对发出修饰器的类型元数据启用实验支持。",
"Enum_0_used_before_its_declaration_2450": "枚举“{0}”用于其声明前。",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "枚举声明只能与命名空间或其他枚举声明合并。",
"Enum_declarations_must_all_be_const_or_non_const_2473": "枚举声明必须全为常数或非常数。",
"Enum_member_expected_1132": "应为枚举成员。",
"Enum_member_must_have_initializer_1061": "枚举成员必须具有初始化表达式。",
diff --git a/lib/zh-TW/diagnosticMessages.generated.json b/lib/zh-TW/diagnosticMessages.generated.json
index c44acb2bd94..b73d983ae22 100644
--- a/lib/zh-TW/diagnosticMessages.generated.json
+++ b/lib/zh-TW/diagnosticMessages.generated.json
@@ -95,9 +95,12 @@
"Accessors_must_both_be_abstract_or_non_abstract_2676": "存取子必須兩者均為抽象或非抽象。",
"Add_0_to_existing_import_declaration_from_1_90015": "從 \"{1}\" 將 '{0}' 新增至現有的匯入宣告",
"Add_async_modifier_to_containing_function_90029": "將 async 修飾詞新增至包含的函式",
+ "Add_definite_assignment_assertion_to_property_0_95020": "將明確指派判斷提示新增至屬性 '{0}'",
"Add_index_signature_for_property_0_90017": "為屬性 '{0}' 新增索引簽章",
+ "Add_initializer_to_property_0_95019": "將初始設定式新增至屬性 '{0}'",
"Add_missing_super_call_90001": "新增遺漏的 'super()' 呼叫",
"Add_this_to_unresolved_variable_90008": "將 'this' 新增至未解析的變數",
+ "Add_undefined_type_to_property_0_95018": "將 'undefined' 類型新增至屬性 '{0}'",
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "新增 tsconfig.json 檔案有助於組織同時包含 TypeScript 及 JavaScript 檔案的專案。若要深入了解,請前往 https://aka.ms/tsconfig。",
"Additional_Checks_6176": "其他檢查",
"Advanced_Options_6178": "進階選項",
@@ -324,6 +327,7 @@
"Enables_experimental_support_for_ES7_decorators_6065": "啟用 ES7 裝飾項目的實驗支援。",
"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "啟用實驗支援以發出裝飾項目類型的中繼資料。",
"Enum_0_used_before_its_declaration_2450": "列舉 '{0}' 的位置在其宣告之前。",
+ "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "列舉宣告只能與命名空間或其他列舉宣告合併。",
"Enum_declarations_must_all_be_const_or_non_const_2473": "列舉宣告必須都是 const 或非 const。",
"Enum_member_expected_1132": "必須是列舉成員。",
"Enum_member_must_have_initializer_1061": "列舉成員必須有初始設定式。",