diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index 7271e1a2328..8647baaf9ee 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "Přidat inicializační výraz k vlastnosti {0}", "Add_initializers_to_all_uninitialized_properties_95027": "Přidat inicializátory do všech neinicializovaných vlastností", "Add_missing_super_call_90001": "Přidat chybějící volání metody super()", + "Add_missing_typeof_95052": "Přidat chybějící typeof", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Přidat kvalifikátor do všech nerozpoznaných proměnných odpovídajících názvu členu", "Add_to_all_uncalled_decorators_95044": "Přidat () do všech nevolaných dekorátorů", "Add_ts_ignore_to_all_error_messages_95042": "Přidat @ts-ignore do všech chybových zpráv", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Všechny deklarace abstraktní metody musí jít po sobě.", "All_destructured_elements_are_unused_6198": "Žádný z destrukturovaných elementů se nepoužívá.", "All_imports_in_import_declaration_are_unused_6192": "Žádné importy z deklarace importu se nepoužívají.", + "All_variables_are_unused_6199": "Žádná z proměnných se nepoužívá.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Povolte výchozí importy z modulů bez výchozího exportu. Nebude to mít vliv na generování kódu, jenom na kontrolu typů.", "Allow_javascript_files_to_be_compiled_6102": "Povolí kompilaci souborů javascript.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Když se zadá příznak --isolatedModules, nepovolují se ambientní výčty.", @@ -273,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Konstruktor třídy {0} je chráněný a dostupný jenom v rámci deklarace třídy.", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory odvozených tříd musí obsahovat volání příkazu super.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Není zadaný obsažený soubor a nedá se určit kořenový adresář – přeskakuje se vyhledávání ve složce node_modules.", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "Převést všechny funkce konstruktoru na třídy", "Convert_all_require_to_import_95048": "Převést všechna volání require na import", "Convert_all_to_default_imports_95035": "Převést vše na výchozí importy", @@ -708,10 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Odkazovaný projekt {0} musí mít nastavení \"composite\": true.", "Remove_all_unreachable_code_95051": "Odebrat veškerý nedosažitelný kód", + "Remove_all_unused_labels_95054": "Odebrat všechny nepoužívané popisky", "Remove_declaration_for_Colon_0_90004": "Odebrat deklaraci pro {0}", "Remove_destructuring_90009": "Odebrat destrukci", "Remove_import_from_0_90005": "Odebrat import z {0}", "Remove_unreachable_code_95050": "Odebrat nedosažitelný kód", + "Remove_unused_label_95053": "Odebrat nepoužitý popisek", + "Remove_variable_statement_90010": "Odebrat příkaz proměnné", "Replace_import_with_0_95015": "Nahradí import použitím: {0}.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Oznámí se chyba, když některé cesty kódu ve funkci nevracejí hodnotu.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Oznámí se chyby v případech fallthrough v příkazu switch.", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 61c5a4bc241..deb7e9108e3 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "Initialisierer zu Eigenschaft \"{0}\" hinzufügen", "Add_initializers_to_all_uninitialized_properties_95027": "Allen nicht initialisierten Eigenschaften Initialisierer hinzufügen", "Add_missing_super_call_90001": "Fehlenden super()-Aufruf hinzufügen", + "Add_missing_typeof_95052": "Fehlenden \"typeof\" hinzufügen", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Allen nicht aufgelösten Variablen, die einem Membernamen entsprechen, Qualifizierer hinzufügen", "Add_to_all_uncalled_decorators_95044": "Allen nicht aufgerufenen Decorators \"()\" hinzufügen", "Add_ts_ignore_to_all_error_messages_95042": "Allen Fehlermeldungen \"@ts-ignore\" hinzufügen", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Alle Deklarationen einer abstrakten Methode müssen aufeinanderfolgend sein.", "All_destructured_elements_are_unused_6198": "Alle destrukturierten Elemente werden nicht verwendet.", "All_imports_in_import_declaration_are_unused_6192": "Keiner der Importe in der Importdeklaration wird verwendet.", + "All_variables_are_unused_6199": "Alle Variablen werden nicht verwendet.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Standardimporte von Modulen ohne Standardexport zulassen. Dies wirkt sich nicht auf die Codeausgabe aus, lediglich auf die Typprüfung.", "Allow_javascript_files_to_be_compiled_6102": "Kompilierung von JavaScript-Dateien zulassen.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "const-Umgebungsenumerationen sind unzulässig, wenn das Flag \"-isolatedModules\" angegeben wird.", @@ -273,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Der Konstruktor der Klasse \"{0}\" ist geschützt. Auf ihn kann nur innerhalb der Klassendeklaration zugegriffen werden.", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktoren für abgeleitete Klassen müssen einen Aufruf \"super\" enthalten.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Die enthaltene Datei wird nicht angegeben, und das Stammverzeichnis kann nicht ermittelt werden. Die Suche im Ordner \"node_modules\" wird übersprungen.", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "Alle Konstruktorfunktionen in Klassen konvertieren", "Convert_all_require_to_import_95048": "Alle Aufrufe von \"require\" in \"import\" konvertieren", "Convert_all_to_default_imports_95035": "Alle in Standardimporte konvertieren", @@ -708,10 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "Die Ausgabestruktur in das Verzeichnis umleiten.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Das referenzierte Projekt \"{0}\" muss für die Einstellung \"composite\" den Wert TRUE aufweisen.", "Remove_all_unreachable_code_95051": "Gesamten nicht erreichbaren Code entfernen", + "Remove_all_unused_labels_95054": "Alle nicht verwendeten Bezeichnungen entfernen", "Remove_declaration_for_Colon_0_90004": "Deklaration entfernen für: {0}", "Remove_destructuring_90009": "Destrukturierung entfernen", "Remove_import_from_0_90005": "Import aus \"{0}\" entfernen", "Remove_unreachable_code_95050": "Nicht erreichbaren Code entfernen", + "Remove_unused_label_95053": "Nicht verwendete Bezeichnung entfernen", + "Remove_variable_statement_90010": "Variablenanweisung entfernen", "Replace_import_with_0_95015": "Ersetzen Sie den Import durch \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Fehler melden, wenn nicht alle Codepfade in der Funktion einen Wert zurückgeben.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Für FallTrough-Fälle in switch-Anweisung Fehler melden.", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 3ea2129b89b..72b35dcaa1e 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -735,6 +735,12 @@ + + + + + + @@ -1659,6 +1665,12 @@ + + + + + + @@ -2073,6 +2085,12 @@ + + + + + + @@ -4305,6 +4323,12 @@ + + + + + + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 9d6ee4cc1f9..d5a4ef792e4 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -106,7 +106,7 @@ "Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"", "Add_initializers_to_all_uninitialized_properties_95027": "Agregar inicializadores a todas las propiedades sin inicializar", "Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta", - "Add_missing_typeof_95052": "Agregar el objeto typeof que falta", + "Add_missing_typeof_95052": "Agregar el elemento \"typeof\" que falta", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Agregar un calificador a todas las variables no resueltas que coincidan con un nombre de miembro", "Add_to_all_uncalled_decorators_95044": "Agregar \"()\" a todos los elementos Decorator a los que no se llama", "Add_ts_ignore_to_all_error_messages_95042": "Agregar \"@ts-ignore\" a todos los mensajes de error", @@ -120,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas las declaraciones de un método abstracto deben ser consecutivas.", "All_destructured_elements_are_unused_6198": "Todos los elementos desestructurados están sin utilizar.", "All_imports_in_import_declaration_are_unused_6192": "Todas las importaciones de la declaración de importación están sin utilizar.", + "All_variables_are_unused_6199": "Todas las variables son no utilizadas.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permitir las importaciones predeterminadas de los módulos sin exportación predeterminada. Esto no afecta a la emisión de código, solo a la comprobación de tipos.", "Allow_javascript_files_to_be_compiled_6102": "Permitir que se compilen los archivos de JavaScript.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "No se permiten enumeraciones const de ambiente cuando se proporciona la marca \"--isolatedModules\".", @@ -274,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "El constructor de la clase '{0}' está protegido y solo es accesible desde la declaración de la clase.", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Los constructores de las clases derivadas deben contener una llamada a \"super\".", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "El archivo contenedor no se ha especificado y no se puede determinar el directorio raíz. Se omitirá la búsqueda en la carpeta 'node_modules'.", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "Convertir todas las funciones de constructor en clases", "Convert_all_require_to_import_95048": "Convertir todas las repeticiones de \"require\" en \"import\"", "Convert_all_to_default_imports_95035": "Convertir todo en importaciones predeterminadas", @@ -709,12 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "El proyecto \"{0}\" al que se hace referencia debe tener el valor \"composite\": true.", "Remove_all_unreachable_code_95051": "Quitar todo el código inaccesible", - "Remove_all_unused_labels_95054": "Remove all unused labels", + "Remove_all_unused_labels_95054": "Quitar todas las etiquetas no utilizadas", "Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\"", "Remove_destructuring_90009": "Quitar la desestructuración", "Remove_import_from_0_90005": "Quitar importación de \"{0}\"", "Remove_unreachable_code_95050": "Quitar el código inaccesible", - "Remove_unused_label_95053": "Remove unused label", + "Remove_unused_label_95053": "Quitar etiqueta no utilizada", + "Remove_variable_statement_90010": "Quitar la declaración de variable", "Replace_import_with_0_95015": "Reemplazar importación por \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Notificar errores de los casos de fallthrough en la instrucción switch.", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 23f0d175862..db1f894b919 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -106,7 +106,7 @@ "Add_initializer_to_property_0_95019": "Ajouter un initialiseur à la propriété '{0}'", "Add_initializers_to_all_uninitialized_properties_95027": "Ajouter des initialiseurs à toutes les propriétés non initialisées", "Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'", - "Add_missing_typeof_95052": "Ajouter un typeof manquant", + "Add_missing_typeof_95052": "Ajouter un 'typeof' manquant", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Ajouter un qualificateur à toutes les variables non résolues correspondant à un nom de membre", "Add_to_all_uncalled_decorators_95044": "Ajouter '()' à tous les décorateurs non appelés", "Add_ts_ignore_to_all_error_messages_95042": "Ajouter '@ts-ignore' à tous les messages d'erreur", @@ -120,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Toutes les déclarations d'une méthode abstraite doivent être consécutives.", "All_destructured_elements_are_unused_6198": "Tous les éléments déstructurés sont inutilisés.", "All_imports_in_import_declaration_are_unused_6192": "Les importations de la déclaration d'importation ne sont pas toutes utilisées.", + "All_variables_are_unused_6199": "Toutes les variables sont inutilisées.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Autorisez les importations par défaut à partir des modules sans exportation par défaut. Cela n'affecte pas l'émission du code, juste le contrôle de type.", "Allow_javascript_files_to_be_compiled_6102": "Autorisez la compilation des fichiers JavaScript.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Les enums const ambiants ne sont pas autorisés quand l'indicateur '--isolatedModules' est fourni.", @@ -709,10 +710,13 @@ "Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Le projet référencé '{0}' doit avoir le paramètre \"composite\" avec la valeur true.", "Remove_all_unreachable_code_95051": "Supprimer tout le code inaccessible", + "Remove_all_unused_labels_95054": "Supprimer toutes les étiquettes inutilisées", "Remove_declaration_for_Colon_0_90004": "Supprimer la déclaration pour : '{0}'", "Remove_destructuring_90009": "Supprimer la déstructuration", "Remove_import_from_0_90005": "Supprimer l'importation de '{0}'", "Remove_unreachable_code_95050": "Supprimer le code inaccessible", + "Remove_unused_label_95053": "Supprimer l'étiquette inutilisée", + "Remove_variable_statement_90010": "Supprimer l'instruction de variable", "Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.", diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index b7463e378ef..70255794d62 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "Aggiungere l'inizializzatore alla proprietà '{0}'", "Add_initializers_to_all_uninitialized_properties_95027": "Aggiungere gli inizializzatori a tutte le proprietà non inizializzate", "Add_missing_super_call_90001": "Aggiungere la chiamata mancante a 'super()'", + "Add_missing_typeof_95052": "Aggiungere l'elemento 'typeof' mancante", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Aggiungere il qualificatore a tutte le variabili non risolte corrispondenti a un nome di membro", "Add_to_all_uncalled_decorators_95044": "Aggiungere '()' a tutti gli elementi Decorator non chiamati", "Add_ts_ignore_to_all_error_messages_95042": "Aggiungere '@ts-ignore' a tutti i messaggi di errore", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Tutte le dichiarazioni di un metodo astratto devono essere consecutive.", "All_destructured_elements_are_unused_6198": "Tutti gli elementi destrutturati sono inutilizzati.", "All_imports_in_import_declaration_are_unused_6192": "Tutte le importazioni nella dichiarazione di importazione sono inutilizzate.", + "All_variables_are_unused_6199": "Tutte le variabili sono inutilizzate.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Consente di eseguire importazioni predefinite da moduli senza esportazione predefinita. Non influisce sulla creazione del codice ma solo sul controllo dei tipi.", "Allow_javascript_files_to_be_compiled_6102": "Consente la compilazione di file JavaScript.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Le enumerazioni const di ambiente non sono consentite quando viene specificato il flag '--isolatedModules'.", @@ -273,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Il costruttore della classe '{0}' è protetto e accessibile solo all'interno della dichiarazione di classe.", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "I costruttori di classi derivate devono contenere una chiamata 'super'.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Il file contenitore non è specificato e non è possibile determinare la directory radice. La ricerca nella cartella 'node_modules' verrà ignorata.", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "Convertire tutte le funzioni di costruttore in classi", "Convert_all_require_to_import_95048": "Convertire tutte le occorrenze di 'require' in 'import'", "Convert_all_to_default_imports_95035": "Convertire tutte le impostazioni predefinite", @@ -708,10 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "Reindirizza la struttura di output alla directory.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Il progetto di riferimento '{0}' deve includere l'impostazione \"composite\": true.", "Remove_all_unreachable_code_95051": "Rimuovere tutto il codice non eseguibile", + "Remove_all_unused_labels_95054": "Rimuovere tutte le etichette inutilizzate", "Remove_declaration_for_Colon_0_90004": "Rimuovere la dichiarazione per '{0}'", "Remove_destructuring_90009": "Rimuovere la destrutturazione", "Remove_import_from_0_90005": "Rimuovere l'importazione da '{0}'", "Remove_unreachable_code_95050": "Rimuovere il codice non eseguibile", + "Remove_unused_label_95053": "Rimuovere l'etichetta inutilizzata", + "Remove_variable_statement_90010": "Rimuovere l'istruzione di variabile", "Replace_import_with_0_95015": "Sostituire l'importazione con '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Segnala l'errore quando non tutti i percorsi del codice nella funzione restituiscono un valore.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Segnala errori per i casi di fallthrough nell'istruzione switch.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index 6189d07adce..a0e226ec3b6 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "プロパティ '{0}' に初期化子を追加します", "Add_initializers_to_all_uninitialized_properties_95027": "初期化されていないすべてのプロパティに初期化子を追加します", "Add_missing_super_call_90001": "欠落している 'super()' 呼び出しを追加する", + "Add_missing_typeof_95052": "不足している 'typeof' を追加します", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "メンバー名と一致するすべての未解決の変数に修飾子を追加します", "Add_to_all_uncalled_decorators_95044": "呼び出されていないすべてのデコレーターに '()' を追加します", "Add_ts_ignore_to_all_error_messages_95042": "すべてのエラー メッセージに '@ts-ignore' を追加します", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象メソッドの宣言はすべて連続している必要があります。", "All_destructured_elements_are_unused_6198": "非構造化要素はいずれも使用されていません。", "All_imports_in_import_declaration_are_unused_6192": "インポート宣言内のインポートはすべて未使用です。", + "All_variables_are_unused_6199": "すべての変数は未使用です。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "既定のエクスポートがないモジュールからの既定のインポートを許可します。これは、型チェックのみのため、コード生成には影響を与えません。", "Allow_javascript_files_to_be_compiled_6102": "javascript ファイルのコンパイルを許可します。", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' フラグが指定されている場合、アンビエント const 列挙型は使用できません。", @@ -273,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "クラス '{0}' のコンストラクターは保護されており、クラス宣言内でのみアクセス可能です。", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生クラスのコンストラクターには 'super' の呼び出しを含める必要があります。", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "包含するファイルが指定されていないため、ルート ディレクトリを決定できません。'node_modules' フォルダーのルックアップをスキップします。", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "すべてのコンストラクター関数をクラスに変換します", "Convert_all_require_to_import_95048": "'require' をすべて 'import' に変換", "Convert_all_to_default_imports_95035": "すべてを既定のインポートに変換します", @@ -708,10 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "参照されているプロジェクト '{0}' には、設定 \"composite\": true が必要です。", "Remove_all_unreachable_code_95051": "到達できないコードをすべて削除します", + "Remove_all_unused_labels_95054": "すべての未使用のラベルを削除します", "Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除する: '{0}'", "Remove_destructuring_90009": "非構造化を削除します", "Remove_import_from_0_90005": "'{0}' からのインポートを削除", "Remove_unreachable_code_95050": "到達できないコードを削除します", + "Remove_unused_label_95053": "未使用のラベルを削除します", + "Remove_variable_statement_90010": "変数のステートメントを削除します", "Replace_import_with_0_95015": "インポートを '{0}' に置換します。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "関数の一部のコード パスが値を返さない場合にエラーを報告します。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch ステートメントに case のフォールスルーがある場合にエラーを報告します。", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index 9ab72b1379f..89dbff7f2e4 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "'{0}' 속성에 이니셜라이저 추가", "Add_initializers_to_all_uninitialized_properties_95027": "초기화되지 않은 모든 속성에 이니셜라이저 추가", "Add_missing_super_call_90001": "누락된 'super()' 호출 추가", + "Add_missing_typeof_95052": "누락된 'typeof' 추가", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "멤버 이름과 일치하는 모든 확인되지 않은 변수에 한정자 추가", "Add_to_all_uncalled_decorators_95044": "호출되지 않는 모든 데코레이터에 '()' 추가", "Add_ts_ignore_to_all_error_messages_95042": "모든 오류 메시지에 '@ts-ignore' 추가", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "추상 메서드의 모든 선언은 연속적이어야 합니다.", "All_destructured_elements_are_unused_6198": "구조 파괴된 요소가 모두 사용되지 않습니다.", "All_imports_in_import_declaration_are_unused_6192": "가져오기 선언의 모든 가져오기가 사용되지 않습니다.", + "All_variables_are_unused_6199": "모든 변수가 사용되지 않습니다.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "기본 내보내기가 없는 모듈에서 기본 가져오기를 허용합니다. 여기서는 코드 내보내기에는 영향을 주지 않고 형식 검사만 합니다.", "Allow_javascript_files_to_be_compiled_6102": "Javascript 파일을 컴파일하도록 허용합니다.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' 플래그가 제공된 경우 앰비언트 const 열거형이 허용되지 않습니다.", @@ -273,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "'{0}' 클래스의 생성자는 protected이며 클래스 선언 내에서만 액세스할 수 있습니다.", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "파생 클래스의 생성자는 'super' 호출을 포함해야 합니다.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "포함 파일이 지정되지 않았고 루트 디렉터리를 확인할 수 없어 'node_modules' 폴더 조회를 건너뜁니다.", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "모든 생성자 함수를 클래스로 변환", "Convert_all_require_to_import_95048": "모든 'require'를 'import'로 변환", "Convert_all_to_default_imports_95035": "모든 항목을 기본 가져오기로 변환", @@ -708,10 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "참조되는 프로젝트 '{0}'에는 \"composite\": true 설정이 있어야 합니다.", "Remove_all_unreachable_code_95051": "접근할 수 없는 코드 모두 제거", + "Remove_all_unused_labels_95054": "사용되지 않는 레이블 모두 제거", "Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언 제거", "Remove_destructuring_90009": "구조 파괴 제거", "Remove_import_from_0_90005": "'{0}'에서 가져오기 제거", "Remove_unreachable_code_95050": "접근할 수 없는 코드 제거", + "Remove_unused_label_95053": "사용되지 않는 레이블 제거", + "Remove_variable_statement_90010": "변수 문 제거", "Replace_import_with_0_95015": "가져오기를 '{0}'(으)로 바꿉니다.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "함수의 일부 코드 경로가 값을 반환하지 않는 경우 오류를 보고합니다.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch 문의 fallthrough case에 대한 오류를 보고합니다.", diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 7a5316e7673..4b90ab6744f 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "Dodaj inicjator do właściwości „{0}”", "Add_initializers_to_all_uninitialized_properties_95027": "Dodaj inicjatory do wszystkich niezainicjowanych właściwości", "Add_missing_super_call_90001": "Dodaj brakujące wywołanie „super()”", + "Add_missing_typeof_95052": "Dodaj brakujący element „typeof”", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Dodaj kwalifikator do wszystkich nierozpoznanych zmiennych pasujących do nazwy składowej", "Add_to_all_uncalled_decorators_95044": "Dodaj element „()” do wszystkich niewywoływanych dekoratorów", "Add_ts_ignore_to_all_error_messages_95042": "Dodaj element „@ts-ignore” do wszystkich komunikatów o błędach", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Wszystkie deklaracje metody abstrakcyjnej muszą występować obok siebie.", "All_destructured_elements_are_unused_6198": "Wszystkie elementy, których strukturę usunięto, są nieużywane.", "All_imports_in_import_declaration_are_unused_6192": "Wszystkie importy w deklaracji importu są nieużywane.", + "All_variables_are_unused_6199": "Wszystkie zmienne są nieużywane.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Zezwalaj na domyślne importy z modułów bez domyślnego eksportu. To nie wpływa na emitowanie kodu, a tylko na sprawdzanie typów.", "Allow_javascript_files_to_be_compiled_6102": "Zezwalaj na kompilowanie plików JavaScript.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Otaczające wyliczenia ze specyfikacją const nie są dozwolone w przypadku podania flagi „--isolatedModules”.", @@ -273,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Konstruktor klasy „{0}” jest chroniony i dostępny tylko w ramach deklaracji klasy.", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory klas pochodnych muszą zawierać wywołanie „super”.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Nie podano pliku zawierającego i nie można określić katalogu głównego. Pomijanie wyszukiwania w folderze „node_modules”.", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "Przekonwertuj wszystkie funkcje konstruktora na klasy", "Convert_all_require_to_import_95048": "Konwertuj wszystkie wywołania „require” na wywołania „import”", "Convert_all_to_default_imports_95035": "Przekonwertuj wszystko na domyślne importowanie", @@ -708,10 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "Przekieruj strukturę wyjściową do katalogu.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Przywoływany projekt „{0}” musi mieć ustawienie „composite” o wartości true.", "Remove_all_unreachable_code_95051": "Usuń cały nieosiągalny kod", + "Remove_all_unused_labels_95054": "Usuń wszystkie nieużywane etykiety", "Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”", "Remove_destructuring_90009": "Usuń usuwanie struktury", "Remove_import_from_0_90005": "Usuń import z „{0}”", "Remove_unreachable_code_95050": "Usuń nieosiągalny kod", + "Remove_unused_label_95053": "Usuń nieużywaną etykietę", + "Remove_variable_statement_90010": "Usuń instrukcję zmiennej", "Replace_import_with_0_95015": "Zamień import na element „{0}”.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index dc13cb5f575..525dbd9ecff 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -1363,7 +1363,7 @@ declare namespace ts.server.protocol { } interface CompletionEntryIdentifier { name: string; - source: string; + source?: string; } /** * Completion entry details request; value of command field is @@ -1403,7 +1403,7 @@ declare namespace ts.server.protocol { /** * Optional modifiers for the kind (such as 'public'). */ - kindModifiers: string; + kindModifiers?: string; /** * A string that is used for comparing completion items so that they can be ordered. This * is often the same as the name but may be different in certain circumstances. @@ -1460,11 +1460,11 @@ declare namespace ts.server.protocol { /** * Documentation strings for the symbol. */ - documentation: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; /** * JSDoc tags for the symbol. */ - tags: JSDocTagInfo[]; + tags?: JSDocTagInfo[]; /** * The associated code actions for this entry */ diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index fd953b416a9..68737ea15f1 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -106,7 +106,7 @@ "Add_initializer_to_property_0_95019": "Adicionar inicializador à propriedade '{0}'", "Add_initializers_to_all_uninitialized_properties_95027": "Adicionar inicializadores a todas as propriedades não inicializadas", "Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente", - "Add_missing_typeof_95052": "Adicionar typeof ausente", + "Add_missing_typeof_95052": "Adicionar 'typeof' ausente", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Adicionar um qualificador a todas as variáveis não resolvidas correspondentes a um nome de membro", "Add_to_all_uncalled_decorators_95044": "Adicionar '()' a todos os decoradores não chamados", "Add_ts_ignore_to_all_error_messages_95042": "Adicionar '@ts-ignore' a todas as mensagens de erro", @@ -120,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas as declarações de um método abstrato devem ser consecutivas.", "All_destructured_elements_are_unused_6198": "Todos os elementos desestruturados são inutilizados.", "All_imports_in_import_declaration_are_unused_6192": "Nenhuma das importações na declaração de importação está sendo utilizada.", + "All_variables_are_unused_6199": "Nenhuma das variáveis está sendo utilizada.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permita importações padrão de módulos sem exportação padrão. Isso não afeta a emissão do código, apenas a verificação de digitação.", "Allow_javascript_files_to_be_compiled_6102": "Permita que arquivos javascript sejam compilados.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "As enumerações de constante de ambiente não são permitidas quando o sinalizador '--isolatedModules' é fornecido.", @@ -274,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "O construtor de classe '{0}' é protegido e somente acessível na declaração de classe.", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Construtores para classes derivadas devem conter uma chamada 'super'.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "O arquivo contido não foi especificado e o diretório raiz não pode ser determinado, ignorando a pesquisa na pasta 'node_modules'.", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "Converter todas as funções de construtor em classes", "Convert_all_require_to_import_95048": "Converter todos os 'require' em 'import'", "Convert_all_to_default_imports_95035": "Converter tudo para importações padrão", @@ -709,10 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "Redirecione a estrutura de saída para o diretório.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "O projeto referenciado '{0}' deve ter a configuração de \"composite\": true.", "Remove_all_unreachable_code_95051": "Remover todo o código inacessível", + "Remove_all_unused_labels_95054": "Remover todos os rótulos não utilizados", "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", "Remove_destructuring_90009": "Remover desestruturação", "Remove_import_from_0_90005": "Remover importação do '{0}'", "Remove_unreachable_code_95050": "Remover código inacessível", + "Remove_unused_label_95053": "Remover rótulo não utilizado", + "Remove_variable_statement_90010": "Remover instrução de variável", "Replace_import_with_0_95015": "Substitua a importação com '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Relate erro quando nem todos os caminhos de código na função retornarem um valor.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Relate erros para casos de fallthrough na instrução switch.", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index dc4efb499e5..a2fb49040e3 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"", "Add_initializers_to_all_uninitialized_properties_95027": "Добавить инициализаторы ко всем неинициализированным свойствам", "Add_missing_super_call_90001": "Добавьте отсутствующий вызов \"super()\"", + "Add_missing_typeof_95052": "Добавить отсутствующий \"typeof\"", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Добавить квалификатор ко всем неразрешенным переменным, соответствующим имени члена", "Add_to_all_uncalled_decorators_95044": "Добавить \"()\" ко всем невызванным декораторам", "Add_ts_ignore_to_all_error_messages_95042": "Добавить \"@ts-ignore\" ко всем сообщениям об ошибках", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Все объявления абстрактных методов должны быть последовательными.", "All_destructured_elements_are_unused_6198": "Все деструктурированные элементы не используются.", "All_imports_in_import_declaration_are_unused_6192": "Ни один из импортов в объявлении импорта не используется.", + "All_variables_are_unused_6199": "Ни одна переменная не используется.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Разрешить импорт по умолчанию из модулей без экспорта по умолчанию. Это не повлияет на выведение кода — только на проверку типов.", "Allow_javascript_files_to_be_compiled_6102": "Разрешить компиляцию файлов javascript.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Перечисление внешних констант не разрешено, если задан флаг \"--isolatedModules\".", @@ -708,10 +710,13 @@ "Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Указанный в ссылке проект \"{0}\" должен иметь следующее значение параметра composite: true.", "Remove_all_unreachable_code_95051": "Удалить весь недостижимый код", + "Remove_all_unused_labels_95054": "Удалить все неиспользуемые метки", "Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\"", "Remove_destructuring_90009": "Удалить деструктурирование", "Remove_import_from_0_90005": "Удалить импорт из \"{0}\"", "Remove_unreachable_code_95050": "Удалить недостижимый код", + "Remove_unused_label_95053": "Удалить неиспользуемую метку", + "Remove_variable_statement_90010": "Удалить оператор с переменной", "Replace_import_with_0_95015": "Замена импорта на \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index d037f7d0d20..338fcfecb23 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "'{0}' özelliğine başlatıcı ekle", "Add_initializers_to_all_uninitialized_properties_95027": "Tüm başlatılmamış özelliklere başlatıcılar ekle", "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle", + "Add_missing_typeof_95052": "Eksik 'typeof' öğesini ekle", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Bir üye adıyla eşleşen tüm çözülmemiş değişkenlere niteleyici ekle", "Add_to_all_uncalled_decorators_95044": "Çağrılmayan tüm dekoratörlere '()' ekle", "Add_ts_ignore_to_all_error_messages_95042": "Tüm hata iletilerine '@ts-ignore' ekle", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.", "All_destructured_elements_are_unused_6198": "Yok edilen öğelerin hiçbiri kullanılmamış.", "All_imports_in_import_declaration_are_unused_6192": "İçeri aktarma bildirimindeki hiçbir içeri aktarma kullanılmadı.", + "All_variables_are_unused_6199": "Hiçbir değişken kullanılmıyor.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", "Allow_javascript_files_to_be_compiled_6102": "Javascript dosyalarının derlenmesine izin ver.", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' bayrağı sağlandığında çevresel const sabit listesi değerlerine izin verilmez.", @@ -273,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "'{0}' sınıfının oluşturucusu korumalı olduğundan, oluşturucuya yalnızca sınıf bildiriminden erişilebilir.", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Türetilmiş sınıflara ilişkin oluşturucular bir 'super' çağrısı içermelidir.", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Kapsayıcı dosya belirtilmedi ve kök dizini belirlenemiyor; 'node_modules' klasöründe arama atlanıyor.", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "Tüm oluşturucu işlevleri sınıflara dönüştür", "Convert_all_require_to_import_95048": "Tüm 'require' öğelerini 'import' olarak dönüştür", "Convert_all_to_default_imports_95035": "Tümünü varsayılan içeri aktarmalara dönüştür", @@ -708,10 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "Çıktı yapısını dizine yeniden yönlendir.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Başvurulan proje '{0}' \"composite\": true ayarına sahip olmalıdır.", "Remove_all_unreachable_code_95051": "Tüm erişilemeyen kodları kaldır", + "Remove_all_unused_labels_95054": "Kullanılmayan tüm etiketleri kaldır", "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır", "Remove_destructuring_90009": "Yıkmayı kaldır", "Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır", "Remove_unreachable_code_95050": "Erişilemeyen kodları kaldır", + "Remove_unused_label_95053": "Kullanılmayan etiketi kaldır", + "Remove_variable_statement_90010": "Değişken deyimini kaldır", "Replace_import_with_0_95015": "İçeri aktarma işlemini '{0}' ile değiştirin.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "İşlevdeki tüm kod yolları bir değer döndürmediğinde hata bildir.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch deyiminde sonraki ifadelere geçiş ile ilgili hataları bildir.", diff --git a/lib/tsc.js b/lib/tsc.js index f39c393bfd1..7cdbc47c20d 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -173,7 +173,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.9"; + ts.versionMajorMinor = "3.0"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { @@ -444,7 +444,7 @@ var ts; return result; } } - Debug.fail(); + return Debug.fail(); } ts.findMap = findMap; function contains(array, value, equalityComparer) { @@ -974,15 +974,6 @@ var ts; return to; } ts.addRange = addRange; - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; function pushIfUnique(array, toAdd, equalityComparer) { if (contains(array, toAdd, equalityComparer)) { return false; @@ -1375,10 +1366,10 @@ var ts; if (value !== undefined && test(value)) return value; if (value && typeof value.kind === "number") { - Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); } else { - Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } } ts.cast = cast; @@ -1458,7 +1449,7 @@ var ts; } ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { - baseIndex = baseIndex || 0; + if (baseIndex === void 0) { baseIndex = 0; } return text.replace(/{(\d+)}/g, function (_match, index) { return Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; @@ -1695,7 +1686,9 @@ var ts; return compareValues(a ? 1 : 0, b ? 1 : 0); } ts.compareBooleans = compareBooleans; - function compareMessageText(text1, text2) { + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; while (text1 && text2) { var string1 = isString(text1) ? text1 : text1.messageText; var string2 = isString(text2) ? text2 : text2.messageText; @@ -1729,6 +1722,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -1747,7 +1748,7 @@ var ts; } ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { - return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { @@ -2207,7 +2208,7 @@ var ts; var subpattern = ""; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); - var lastComponent = lastOrUndefined(components); + var lastComponent = last(components); if (usage !== "exclude" && lastComponent === "**") { return undefined; } @@ -2398,11 +2399,11 @@ var ts; return scriptKind === 1 || scriptKind === 2; } function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { @@ -2576,7 +2577,8 @@ var ts; } Debug.fail = fail; function assertDefined(value, message) { - assert(value !== undefined && value !== null, message); + if (value === undefined || value === null) + return fail(message); return value; } Debug.assertDefined = assertDefined; @@ -2734,10 +2736,7 @@ var ts; ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); - if (ext !== undefined) { - return ext; - } - Debug.fail("File " + path + " has unknown extension."); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; function isAnySupportedFileExtension(path) { @@ -3286,6 +3285,7 @@ var ts; return watchDirectoryRecursively(directoryName, callback); } watchDirectory(directoryName, callback); + return undefined; }; } function createNonPollingWatchFile() { @@ -3516,6 +3516,7 @@ var ts; switch (entryKind) { case 0: return stat.isFile(); case 1: return stat.isDirectory(); + default: return false; } } catch (e) { @@ -4198,7 +4199,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -4526,6 +4527,8 @@ var ts; _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true), Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", true), + Enable_strict_checking_of_any_type: diag(6200, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_any_type_6200", "Enable strict checking of 'any' type."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -4553,7 +4556,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -4634,6 +4637,7 @@ var ts; Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -4703,6 +4707,7 @@ var ts; Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), }; })(ts || (ts = {})); var ts; @@ -5294,8 +5299,9 @@ var ts; return true; } ts.isIdentifierText = isIdentifierText; - function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } + var text = textInitial; var pos; var end; var startPos; @@ -6493,7 +6499,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function packageIdToString(_a) { var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; @@ -6600,6 +6606,19 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { if (text.charCodeAt(commentPos + 1) === 47 && commentPos + 2 < commentEnd && @@ -6669,7 +6688,7 @@ var ts; ts.indexOfNode = indexOfNode; function getEmitFlags(node) { var emitNode = node.emitNode; - return emitNode && emitNode.flags; + return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { @@ -6697,7 +6716,7 @@ var ts; case 12: return node.text; } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { @@ -6791,7 +6810,7 @@ var ts; case 192: return true; case 212: - return parentNode && !ts.isFunctionLike(parentNode); + return !ts.isFunctionLike(parentNode); } return false; } @@ -6892,6 +6911,8 @@ var ts; return entityNameToString(name.left) + "." + entityNameToString(name.right); case 184: return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); } } ts.entityNameToString = entityNameToString; @@ -7086,7 +7107,7 @@ var ts; ts.Debug.assert(node.kind === 71 || node.kind === 145 || node.kind === 184, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 145: case 184: - case 99: + case 99: { var parent = node.parent; if (parent.kind === 164) { return false; @@ -7128,6 +7149,7 @@ var ts; case 188: return false; } + } } return false; } @@ -7308,15 +7330,16 @@ var ts; return ts.filter(objectLiteral.properties, function (property) { if (property.kind === 269) { var propName = getTextOfPropertyName(property.name); - return key === propName || (key2 && key2 === propName); + return key === propName || (!!key2 && key2 === propName); } + return false; }); } ts.getPropertyAssignment = getPropertyAssignment; function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { var expression = tsConfigSourceFile.statements[0].expression; - return ts.isObjectLiteralExpression(expression) && expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); } } ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; @@ -7339,10 +7362,11 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 273); while (true) { node = node.parent; if (!node) { - return undefined; + return ts.Debug.fail(); } switch (node.kind) { case 146: @@ -7518,10 +7542,12 @@ var ts; function childIsDecorated(node, parent) { switch (node.kind) { case 234: - return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); case 153: case 156: - return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + default: + return false; } } ts.childIsDecorated = childIsDecorated; @@ -7664,15 +7690,15 @@ var ts; } ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536); + return !!node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; function isInJsonFile(node) { - return node && !!(node.flags & 16777216); + return !!node && !!(node.flags & 16777216); } ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { - return node && !!(node.flags & 2097152); + return !!node && !!(node.flags & 2097152); } ts.isInJSDoc = isInJSDoc; function isJSDocIndexSignature(node) { @@ -7896,7 +7922,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 243 && node.importClause && !!node.importClause.name; + return node.kind === 243 && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { @@ -7933,16 +7959,18 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 && - node.expression.right; + node.expression.operatorToken.kind === 58 + ? node.expression.right + : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && getSpecialPropertyAssignmentKind(node.expression) !== 0 && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 && - node.expression.right.right; + node.expression.right.operatorToken.kind === 54 + ? node.expression.right.right + : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { @@ -7956,15 +7984,14 @@ var ts; } } function getSingleVariableOfVariableStatement(node) { - return ts.isVariableStatement(node) && - node.declarationList.declarations.length > 0 && - node.declarationList.declarations[0]; + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } function getNestedModuleDeclaration(node) { - return node.kind === 238 && + return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 238 && - node.body; + node.body.kind === 238 + ? node.body + : undefined; } function getJSDocCommentsAndTags(hostNode) { var result; @@ -8045,12 +8072,12 @@ var ts; ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { var last = ts.lastOrUndefined(s.parameters); - return last && isRestParameter(last); + return !!last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || type && type.kind === 284; + return node.dotDotDotToken !== undefined || !!type && type.kind === 284; } ts.isRestParameter = isRestParameter; function getAssignmentTargetKind(node) { @@ -8171,9 +8198,10 @@ var ts; switch (name.kind) { case 71: case 9: - case 8: - if (ts.isDeclaration(name.parent)) { - return name.parent.name === name; + case 8: { + var parent = name.parent; + if (ts.isDeclaration(parent)) { + return parent.name === name; } else if (ts.isQualifiedName(name.parent)) { var tag = name.parent.parent; @@ -8183,6 +8211,7 @@ var ts; var binExp = name.parent.parent; return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; } + } default: return false; } @@ -8357,7 +8386,7 @@ var ts; ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); - return name && isDynamicName(name); + return !!name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -8784,7 +8813,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); + linePos = output.length - s.length + ts.last(lineStartsOfS); } } } @@ -8943,7 +8972,7 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return node && node.kind === 71 && identifierIsThisKeyword(node); + return !!node && node.kind === 71 && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { @@ -9112,12 +9141,12 @@ var ts; lastComment = comment; } if (detachedComments.length) { - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; } } } @@ -9260,7 +9289,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 206 && + if (ts.isExpressionWithTypeArguments(node) && node.parent.token === 85 && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -10035,7 +10064,7 @@ var ts; try { ts.localizedDiagnosticMessages = JSON.parse(fileContents); } - catch (e) { + catch (_a) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); } @@ -11593,7 +11622,8 @@ var ts; } ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { - return !!node.jsDoc && node.jsDoc.length > 0; + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; function hasType(node) { @@ -12208,6 +12238,7 @@ var ts; } ts.isExternalModule = isExternalModule; function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); newSourceFile.flags |= (sourceFile.flags & 1572864); return newSourceFile; @@ -12245,6 +12276,7 @@ var ts; var contextFlags; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); @@ -12426,6 +12458,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -12853,7 +12886,7 @@ var ts; case 14: return true; } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17); @@ -12929,6 +12962,8 @@ var ts; return token() === 29 || token() === 41; case 14: return token() === 27 && lookAhead(nextTokenIsSlash); + default: + return false; } } function isVariableDeclaratorListTerminator() { @@ -13173,6 +13208,7 @@ var ts; case 22: return ts.Diagnostics.Identifier_expected; case 13: return ts.Diagnostics.Identifier_expected; case 14: return ts.Diagnostics.Identifier_expected; + default: return undefined; } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -13263,7 +13299,7 @@ var ts; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(list).literal.kind === 15); + } while (ts.last(list).literal.kind === 15); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } @@ -13571,7 +13607,7 @@ var ts; if (token() === 19 || token() === 27) { return true; } - var idToken; + var idToken = false; while (ts.isModifierKind(token())) { idToken = true; nextToken(); @@ -15570,6 +15606,7 @@ var ts; missing.modifiers = node.modifiers; return finishNode(missing); } + return undefined; } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { @@ -15860,7 +15897,7 @@ var ts; node.name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(node); } - ts.Debug.fail("Should not have attempted to parse class member declaration."); + return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 204); @@ -15899,14 +15936,12 @@ var ts; } function parseHeritageClause() { var tok = token(); - if (tok === 85 || tok === 108) { - var node = createNode(267); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; + ts.Debug.assert(tok === 85 || tok === 108); + var node = createNode(267); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); + return finishNode(node); } function parseExpressionWithTypeArguments() { var node = createNode(206); @@ -16247,8 +16282,8 @@ var ts; } JSDocParser.parseJSDocComment = parseJSDocComment; function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } var content = sourceText; - start = start || 0; var end = length === undefined ? content.length : start + length; length = end - start; ts.Debug.assert(start >= 0); @@ -16551,7 +16586,7 @@ var ts; var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target); + var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -17260,10 +17295,7 @@ var ts; break; } case "amd-dependency": { - context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { - var _b = _a.arguments, name = _b.name, path = _b.path; - return ({ name: name, path: path }); - }); + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); break; } case "amd-module": { @@ -18280,6 +18312,7 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -18321,7 +18354,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217) { addAntecedent(postStatementLabel, currentFlow); @@ -18862,6 +18895,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -19335,7 +19378,8 @@ var ts; } else { var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); - ts.Debug.assert(!!s && !!s.exports); + if (!s || !s.exports) + return ts.Debug.fail(); return action(e.name, s.exports.get(e.name.escapedText)); } } @@ -19480,7 +19524,7 @@ var ts; } function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); + return instanceState === 1 || (instanceState === 2 && !!options.preserveConstEnums); } function checkUnreachable(node) { if (!(currentFlow.flags & 1)) { @@ -19493,13 +19537,13 @@ var ts; (node.kind === 237 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304) && - (node.kind !== 213 || - ts.getCombinedNodeFlags(node.declarationList) & 3 || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -19514,8 +19558,8 @@ var ts; ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { return isExportsOrModuleExportsOrAlias(sourceFile, node) || @@ -20356,11 +20400,11 @@ var ts; } function visitSymbol(symbol) { if (!symbol) { - return; + return false; } var symbolId = ts.getSymbolId(symbol); if (visitedSymbols[symbolId]) { - return; + return false; } visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { @@ -20378,6 +20422,7 @@ var ts; visitSymbol(entity); } }); + return false; } } } @@ -20390,7 +20435,7 @@ var ts; } ts.trace = trace; function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; + return !!compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; function withPackageId(packageId, r) { @@ -20551,14 +20596,13 @@ var ts; } } function secondaryLookup() { - var resolvedFile; var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); + var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -20710,7 +20754,7 @@ var ts; result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; default: - ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -20888,7 +20932,7 @@ var ts; var originalPath = void 0; if (!compilerOptions.preserveSymlinks && resolvedValue) { originalPath = resolvedValue.path; - var path = realPath(resolved_1.value.path, host, traceEnabled); + var path = realPath(resolvedValue.path, host, traceEnabled); if (path === originalPath) { originalPath = undefined; } @@ -20988,7 +21032,7 @@ var ts; function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json"); - return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); } var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -21022,7 +21066,7 @@ var ts; } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, ext: ext }; + return path === undefined ? undefined : { path: path, ext: ext }; } } function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { @@ -21369,6 +21413,7 @@ var ts; var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var strictAny = ts.getStrictOptionValue(compilerOptions, "strictAny"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; @@ -21395,9 +21440,10 @@ var ts; location = ts.getParseTreeNode(location); return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); }, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, @@ -21409,8 +21455,8 @@ var ts; getBaseTypes: getBaseTypes, getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node ? getTypeFromTypeNode(node) : unknownType; }, getParameterType: getTypeAtPosition, @@ -21437,8 +21483,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getShorthandAssignmentValueSymbol(node) : undefined; }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, getExportSymbolOfSymbol: function (symbol) { @@ -21448,8 +21494,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; }, signatureToString: function (signature, enclosingDeclaration, flags, kind) { @@ -21479,41 +21525,41 @@ var ts; getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, - getContextualTypeForArgumentAtIndex: function (node, argIndex) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); }, - getContextualTypeForJsxAttribute: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxAttributeLike); + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); apparentArgumentCount = theArgumentCount; var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; apparentArgumentCount = undefined; return res; }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); }, - isValidPropertyAccessForCompletions: function (node, type, property) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); return !!node && isValidPropertyAccessForCompletions(node, type, property); }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); return declaration ? getSignatureFromDeclaration(declaration) : undefined; }, isImplementationOfOverload: function (node) { @@ -21525,7 +21571,8 @@ var ts; var links = getSymbolLinks(symbol); if (!links.immediateTarget) { var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); links.immediateTarget = getTargetOfAliasDeclaration(node, true); } return links.immediateTarget; @@ -21536,13 +21583,13 @@ var ts; getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); return node ? isOptionalParameter(node) : false; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, @@ -21586,8 +21633,8 @@ var ts; node = ts.getParseTreeNode(node); return node && tryGetThisTypeAt(node); }, - getTypeArgumentConstraint: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file) { @@ -21773,6 +21820,7 @@ var ts; typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); }, buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0; } symbolToString(symbol, enclosingDeclaration, meaning, flags | 4, emitTextWriterWrapper(writer)); }, buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { @@ -22181,7 +22229,7 @@ var ts; if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); @@ -22235,7 +22283,8 @@ var ts; } break; } - return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); } function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { return !!ts.findAncestor(usage, function (current) { @@ -22261,6 +22310,7 @@ var ts; } } } + return false; }); } } @@ -22566,11 +22616,11 @@ var ts; } function checkAndReportErrorForExtendingInterface(errorLocation) { var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64, true)); - if (isError) { + if (expression && resolveEntityName(expression, 64, true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; + return false; } function getEntityNameForExtendingInterface(node) { switch (node.kind) { @@ -22640,7 +22690,8 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 237) ? d : undefined; }); - ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); @@ -22654,7 +22705,7 @@ var ts; } } function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { switch (node.kind) { @@ -22764,6 +22815,7 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { + if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { @@ -22826,6 +22878,7 @@ var ts; return getNodeLinks(expression).resolvedSymbol; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { case 242: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); @@ -22842,17 +22895,18 @@ var ts; return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 241: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); } } function isNonLocalAlias(symbol, excludes) { if (excludes === void 0) { excludes = 67216319 | 67901928 | 1920; } if (!symbol) return false; - return (symbol.flags & (2097152 | excludes)) === 2097152 || (symbol.flags & 2097152 && symbol.flags & 67108864); + return (symbol.flags & (2097152 | excludes)) === 2097152 || !!(symbol.flags & 2097152 && symbol.flags & 67108864); } function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); - return shouldResolve ? resolveAlias(symbol) : symbol; + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); @@ -22860,7 +22914,8 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -22890,7 +22945,8 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); if (node.kind === 248) { checkExpressionCached(node.expression); } @@ -22972,7 +23028,7 @@ var ts; } } else { - ts.Debug.assertNever(name, "Unknown entity name kind."); + throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -23398,7 +23454,7 @@ var ts; } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -23421,13 +23477,18 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { return false; } @@ -23487,7 +23548,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { return { accessibility: 0 }; @@ -23521,6 +23582,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -23602,6 +23666,7 @@ var ts; } } function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0; } return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); function signatureToStringWorker(writer) { var sigOutput; @@ -23619,10 +23684,11 @@ var ts; } } function typeToString(type, enclosingDeclaration, flags, writer) { - if (flags === void 0) { flags = 1048576; } + if (flags === void 0) { flags = 1048576 | 16384; } 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"); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); @@ -23635,6 +23701,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0; } return flags & 9469291; } function createNodeBuilder() { @@ -23699,7 +23766,7 @@ var ts; function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, - flags: flags, + flags: flags || 0, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, @@ -23804,8 +23871,9 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8), undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928, false) : ts.createIdentifier("?"); - return ts.createTypeReferenceNode(name, undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); @@ -23854,7 +23922,7 @@ var ts; if (type.flags & 4194304) { return typeToTypeNodeHelper(type.typeVariable, context); } - ts.Debug.fail("Should be unreachable."); + return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -24086,7 +24154,7 @@ var ts; var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024) { - var decl = ts.firstOrUndefined(propertySymbol.declarations); + var decl = ts.first(propertySymbol.declarations); var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319); if (name && context.tracker.trackSymbol) { context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); @@ -24141,7 +24209,7 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 137 : 134); var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); if (!indexInfo.type && !(context.flags & 2097152)) { context.encounteredError = true; } @@ -24217,7 +24285,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; var dotDotDotToken = isRest ? ts.createToken(24) : undefined; var name = parameterDeclaration @@ -24247,7 +24315,7 @@ var ts; var chain; var isTypeParameter = symbol.flags & 262144; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64)) { - chain = getSymbolChain(symbol, meaning, true); + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, true)); ts.Debug.assert(chain && chain.length > 0); } else { @@ -24272,7 +24340,7 @@ var ts; return accessibleSymbolChain; } if (endOfChain || - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && !(symbol.flags & (2048 | 4096))) { return [symbol]; } @@ -24443,6 +24511,7 @@ var ts; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512)); @@ -24698,22 +24767,22 @@ var ts; } function hasType(target, propertyName) { if (propertyName === 0) { - return getSymbolLinks(target).type; + return !!getSymbolLinks(target).type; } if (propertyName === 2) { - return getSymbolLinks(target).declaredType; + return !!getSymbolLinks(target).declaredType; } if (propertyName === 1) { - return target.resolvedBaseConstructorType; + return !!target.resolvedBaseConstructorType; } if (propertyName === 3) { - return target.resolvedReturnType; + return !!target.resolvedReturnType; } if (propertyName === 4) { var bc = target.resolvedBaseConstraint; - return bc && bc !== circularConstraintType; + return !!bc && bc !== circularConstraintType; } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } function popTypeResolution() { resolutionTargets.pop(); @@ -24721,7 +24790,7 @@ var ts; return resolutionResults.pop(); } function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { case 231: case 232: @@ -24733,8 +24802,7 @@ var ts; default: return true; } - }); - return node && node.parent; + }).parent; } function getTypeOfPrototypeProperty(prototype) { var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); @@ -24832,7 +24900,7 @@ var ts; } return indexerType || anyType; } - var nameType = isLate && checkComputedPropertyName(name); + var nameType = isLate ? checkComputedPropertyName(name) : undefined; var text = isLate ? getLateBoundNameFromType(nameType) : isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : ts.getTextOfPropertyName(name); @@ -25128,7 +25196,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + if (!lastElement || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); @@ -25140,6 +25208,8 @@ var ts; return result; } function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } return pattern.kind === 179 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); @@ -25235,7 +25305,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } else { - ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); } if (!popTypeResolution()) { type = reportCircularityError(symbol); @@ -25431,11 +25501,12 @@ var ts; function check(type) { if (ts.getObjectFlags(type) & (3 | 4)) { var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); + return target === checkBase || ts.some(getBaseTypes(target), check); } else if (type.flags & 262144) { - return ts.forEach(type.types, check); + return ts.some(type.types, check); } + return false; } } function appendTypeParameters(typeParameters, declarations) { @@ -25521,7 +25592,7 @@ var ts; } if (type.flags & 1081344) { var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } @@ -25646,8 +25717,8 @@ var ts; return true; } function isValidBaseType(type) { - return type.flags & (65536 | 134217728 | 1) && !isGenericMappedType(type) || - type.flags & 262144 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return !!(type.flags & (65536 | 134217728 | 1)) && !isGenericMappedType(type) || + !!(type.flags & 262144) && !ts.some(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -25920,7 +25991,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 154 || (returnType && isThislessType(returnType))) && + return (node.kind === 154 || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -25981,7 +26052,7 @@ var ts; } function hasLateBindableName(node) { var name = ts.getNameOfDeclaration(node); - return name && isLateBindableName(name); + return !!name && isLateBindableName(name); } function hasNonBindableDynamicName(node) { return ts.hasDynamicName(node) && !hasLateBindableName(node); @@ -25996,6 +26067,7 @@ var ts; if (type.flags & 96) { return ts.escapeLeadingUnderscores("" + type.value); } + return ts.Debug.fail(); } function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024), "Expected a late-bound symbol."); @@ -26008,8 +26080,7 @@ var ts; symbol.declarations.push(member); } if (symbolFlags & 67216319) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } } @@ -26514,7 +26585,7 @@ var ts; return !!(ts.getObjectFlags(type) & 32 && getMappedTypeModifiers(type) & 4); } function isGenericMappedType(type) { - return ts.getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return !!(ts.getObjectFlags(type) & 32) && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -27072,7 +27143,7 @@ var ts; var hasLiteralTypes = false; var minArgumentCount = 0; var thisParameter = void 0; - var hasThisParameter = void 0; + var hasThisParameter = false; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && @@ -27187,7 +27258,7 @@ var ts; return node.name.kind === 146 && traverse(node.name); default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); } } } @@ -27284,9 +27355,10 @@ var ts; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + var type = getTypeOfSymbol(ts.last(signature.parameters)); if (ts.getObjectFlags(type) & 4 && type.target === globalArrayType) { - return type.typeArguments[0]; + var t = type.typeArguments[0]; + return strictAny && t.flags & 1 ? unknownType : t; } } return anyType; @@ -27580,7 +27652,7 @@ var ts; var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); if (referenceType || assignedType) { - return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; + return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -27631,7 +27703,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return node.flags & 2097152 && node.kind === 161; + return !!(node.flags & 2097152) && node.kind === 161; } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -27678,7 +27750,7 @@ var ts; var indexed = getTypeFromTypeNode(typeArgs[0]); var target = getTypeFromTypeNode(typeArgs[1]); var index = createIndexInfo(target, false); - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); } return anyType; } @@ -28157,16 +28229,19 @@ var ts; return true; } function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); if (includes & 16384) { return neverType; } - if (includes & 1) { - return includes & 33554432 ? wildcardType : anyType; + if (includes & 33554432) { + return wildcardType; + } + if (!strictAny && includes & 1) { + return anyType; + } + if (!strictNullChecks && includes & 12288) { + return includes & 4096 ? undefinedType : nullType; } if (includes & 2 && includes & 32 || includes & 4 && includes & 64 || @@ -28176,6 +28251,9 @@ var ts; if (includes & 67108864 && !(includes & 65536)) { typeSet.push(emptyObjectType); } + if (typeSet.length === 0) { + return anyType; + } if (typeSet.length === 1) { return typeSet[0]; } @@ -28365,12 +28443,12 @@ var ts; var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - t.stringIndexInfo && !t.numberIndexInfo; + !!t.stringIndexInfo && !t.numberIndexInfo; } return false; } function isMappedTypeToNever(type) { - return ts.getObjectFlags(type) & 32 && getTemplateTypeFromMappedType(type) === neverType; + return !!(ts.getObjectFlags(type) & 32) && getTemplateTypeFromMappedType(type) === neverType; } function getSimplifiedType(type) { return type.flags & 1048576 ? getSimplifiedIndexedAccessType(type) : type; @@ -28788,7 +28866,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 8388608 ? type.regularType : type; + return type.flags & 96 && type.flags & 8388608 ? type.regularType : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { var qualifier = typeof value === "number" ? "#" : "@"; @@ -28916,7 +28996,7 @@ var ts; case 71: case 145: var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return (symbol && getDeclaredTypeOfSymbol(symbol)); default: return unknownType; } @@ -29110,21 +29190,21 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; if (ts.findAncestor(node, function (n) { return n.kind === 212 ? "quit" : n === container_3; })) { - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { case 173: - return tp.isThisType; + return !!tp.isThisType; case 71: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; case 164: return true; } - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -29243,9 +29323,9 @@ var ts; case 153: return isContextSensitiveFunctionLikeDeclaration(node); case 183: - return ts.forEach(node.properties, isContextSensitive); + return ts.some(node.properties, isContextSensitive); case 182: - return ts.forEach(node.elements, isContextSensitive); + return ts.some(node.elements, isContextSensitive); case 200: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); @@ -29257,11 +29337,15 @@ var ts; case 190: return isContextSensitive(node.expression); case 262: - return ts.forEach(node.properties, isContextSensitive); - case 261: - return node.initializer && isContextSensitive(node.initializer); - case 264: - return node.expression && isContextSensitive(node.expression); + return ts.some(node.properties, isContextSensitive); + case 261: { + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 264: { + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } } return false; } @@ -29269,7 +29353,7 @@ var ts; if (node.typeParameters) { return false; } - if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } if (node.kind !== 192) { @@ -29278,7 +29362,8 @@ var ts; return true; } } - return node.body.kind === 212 ? false : isContextSensitive(node.body); + var body = node.body; + return body.kind === 212 ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -29486,8 +29571,8 @@ var ts; function isEmptyObjectType(type) { return type.flags & 65536 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 134217728 ? true : - type.flags & 131072 ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 262144 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + type.flags & 131072 ? ts.some(type.types, isEmptyObjectType) : + type.flags & 262144 ? !ts.some(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -29562,7 +29647,7 @@ var ts; if (s & 1024 || t & 1024) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { - if (s & 1) + if (s & 1 && (!strictAny || source === unknownType || t & 65536 && isEmptyObjectType(target))) return true; if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; @@ -29681,6 +29766,7 @@ var ts; return false; } function isRelatedTo(source, target, reportErrors, headMessage) { + if (reportErrors === void 0) { reportErrors = false; } if (source.flags & 96 && source.flags & 8388608) { source = source.regularType; } @@ -29840,7 +29926,8 @@ var ts; var _loop_6 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { - ts.Debug.assert(!!errorNode); + if (!errorNode) + return { value: ts.Debug.fail() }; if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } @@ -29851,8 +29938,9 @@ var ts; var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; - if (ts.isIdentifier(propDeclaration.name)) { - suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); } } if (suggestion !== undefined) { @@ -30427,7 +30515,7 @@ var ts; } } else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { - var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); } else { @@ -30515,7 +30603,7 @@ var ts; return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); } if (isGenericMappedType(source)) { - return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + return (kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); } if (isObjectTypeWithInferableIndex(source)) { var related = -1; @@ -30613,7 +30701,7 @@ var ts; return type.flags & 32768 && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return ts.getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return !!(ts.getObjectFlags(type) & 4) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } function getTypeReferenceId(type, typeParameters, depth) { if (depth === void 0) { depth = 0; } @@ -30821,7 +30909,7 @@ var ts; return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); } function isArrayType(type) { - return ts.getObjectFlags(type) & 4 && type.target === globalArrayType; + return !!(ts.getObjectFlags(type) & 4) && type.target === globalArrayType; } function isArrayLikeType(type) { return ts.getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || @@ -31222,12 +31310,12 @@ var ts; } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); } return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 393216 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 393216) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); @@ -31609,7 +31697,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 16382 | 524288); + return !!constraint && maybeTypeOfKind(constraint, 16382 | 524288); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128); @@ -31629,10 +31717,12 @@ var ts; } function getCovariantInference(inference, context, signature) { var candidates = widenObjectLiteralCandidates(inference.candidates); - var widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; var unwidenedType = context.flags & 1 || inference.priority & 28 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); @@ -31723,7 +31813,8 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 179) { + var parent = element.parent; + if (parent.kind === 179) { var name = element.propertyName || element.name; switch (name.kind) { case 71: @@ -31738,7 +31829,7 @@ var ts; } } else { - return "" + element.parent.elements.indexOf(element); + return "" + parent.elements.indexOf(element); } } function isMatchingReference(source, target) { @@ -31766,7 +31857,7 @@ var ts; } if (source.parent.parent.kind === 231) { var maybeId = source.parent.parent.initializer; - return maybeId && isMatchingReference(maybeId, t.expression); + return !!maybeId && isMatchingReference(maybeId, t.expression); } } return false; @@ -31800,7 +31891,7 @@ var ts; var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -32904,7 +32995,7 @@ var ts; } else if (declaration.kind === 204) { var container = ts.getThisContainer(node, false); - while (container !== undefined) { + while (container.kind !== 273) { if (container.parent === declaration) { if (container.kind === 151 && ts.hasModifier(container, 32)) { getNodeLinks(declaration).flags |= 8388608; @@ -33372,7 +33463,7 @@ var ts; if (funcHasRestParameters && indexOfParameter === (func.parameters.length - 1) && isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + return getTypeOfSymbol(ts.last(contextualSignature.parameters)); } } } @@ -33506,7 +33597,7 @@ var ts; case 6: return false; default: - ts.Debug.assertNever(kind); + return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { @@ -33578,6 +33669,22 @@ var ts; return getContextualType(attribute.parent); } } + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9: + case 8: + case 13: + case 101: + case 86: + case 95: + case 71: + return true; + case 184: + case 190: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); @@ -33591,8 +33698,8 @@ var ts; continue; if (prop.kind !== 269) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -33669,8 +33776,8 @@ var ts; return undefined; } function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -34161,7 +34268,7 @@ var ts; case 71: return ts.isIntrinsicJsxName(tagName.escapedText); default: - ts.Debug.fail(); + return ts.Debug.fail(); } } function checkJsxAttribute(node, checkMode) { @@ -34338,6 +34445,7 @@ var ts; return instantiatedSignatures; } function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (reportErrors === void 0) { reportErrors = false; } if (!node.typeArguments) { return; } @@ -34523,7 +34631,7 @@ var ts; if (!ts.length(instantiatedSignatures)) { return unknownType; } - var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); + var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); @@ -34534,7 +34642,7 @@ var ts; checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(ts.map(instantiatedSignatures, function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, true); })); + return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, true); })); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); @@ -35099,7 +35207,7 @@ var ts; } var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, left, type, prop) - : ts.isInJavaScriptFile(node) && (type.flags & 131072) && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 131072) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); } function getForInVariableSymbol(node) { var initializer = node.initializer; @@ -35230,7 +35338,7 @@ var ts; var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { - index++; + index = index + 1; } else { lastParent = parent; @@ -35266,7 +35374,7 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; var typeArguments; - var callIsIncomplete; + var callIsIncomplete = false; var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { return true; @@ -35275,8 +35383,7 @@ var ts; argCount = args.length; typeArguments = undefined; if (node.template.kind === 201) { - var lastSpan = ts.lastOrUndefined(node.template.templateSpans); - ts.Debug.assert(lastSpan !== undefined); + var lastSpan = ts.last(node.template.templateSpans); callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { @@ -35406,7 +35513,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -35445,7 +35552,7 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { return false; } } @@ -35512,6 +35619,8 @@ var ts; return signature.parameters.length >= 3 ? 3 : 2; case 148: return 3; + default: + return ts.Debug.fail(); } } else { @@ -35555,14 +35664,15 @@ var ts; node.kind === 155 || node.kind === 156) { var element = node; - switch (element.name.kind) { + var name = element.name; + switch (name.kind) { case 71: - return getLiteralType(ts.idText(element.name)); + return getLiteralType(ts.idText(name)); case 8: case 9: - return getLiteralType(element.name.text); + return getLiteralType(name.text); case 146: - var nameType = checkComputedPropertyName(element.name); + var nameType = checkComputedPropertyName(name); if (isTypeAssignableToKind(nameType, 1536)) { return nameType; } @@ -36007,6 +36117,8 @@ var ts; case 155: case 156: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); } } function resolveDecorator(node, candidatesOutArray) { @@ -36027,8 +36139,7 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); invocationErrorRecovery(apparentType, 0); @@ -36076,7 +36187,7 @@ var ts; return ts.length(sigs) ? sigs[0] : unknownSignature; }) || unknownSignature; } - ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); @@ -36096,7 +36207,7 @@ var ts; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; - return symbol && symbol.members !== undefined; + return !!symbol && symbol.members !== undefined; } return false; } @@ -36312,6 +36423,7 @@ var ts; if (node.keywordToken === 91) { return checkImportMetaProperty(node); } + return ts.Debug.assertNever(node.keywordToken); } function checkNewTargetMetaProperty(node) { var container = ts.getNewTargetContainer(node); @@ -36390,9 +36502,9 @@ var ts; } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { - var parameter = ts.lastOrUndefined(signature.parameters); + var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + var contextualParameterType = getTypeOfSymbol(ts.last(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } @@ -36744,7 +36856,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 245; + return !!declaration && declaration.kind === 245; } } } @@ -36862,15 +36974,15 @@ var ts; if (strict && source.flags & (1 | 2048 | 4096 | 8192)) { return false; } - return (kind & 84 && isTypeAssignableTo(source, numberType)) || - (kind & 34 && isTypeAssignableTo(source, stringType)) || - (kind & 136 && isTypeAssignableTo(source, booleanType)) || - (kind & 2048 && isTypeAssignableTo(source, voidType)) || - (kind & 16384 && isTypeAssignableTo(source, neverType)) || - (kind & 8192 && isTypeAssignableTo(source, nullType)) || - (kind & 4096 && isTypeAssignableTo(source, undefinedType)) || - (kind & 512 && isTypeAssignableTo(source, esSymbolType)) || - (kind & 134217728 && isTypeAssignableTo(source, nonPrimitiveType)); + return !!(kind & 84) && isTypeAssignableTo(source, numberType) || + !!(kind & 34) && isTypeAssignableTo(source, stringType) || + !!(kind & 136) && isTypeAssignableTo(source, booleanType) || + !!(kind & 2048) && isTypeAssignableTo(source, voidType) || + !!(kind & 16384) && isTypeAssignableTo(source, neverType) || + !!(kind & 8192) && isTypeAssignableTo(source, nullType) || + !!(kind & 4096) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 512) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 134217728) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { return source.flags & 131072 ? @@ -36878,7 +36990,7 @@ var ts; isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return ts.getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); + return !!(ts.getObjectFlags(type) & 16) && !!type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; @@ -36905,7 +37017,7 @@ var ts; if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 | 1536))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 134217728 | 7372800)) { + if (!(rightType.flags & 1 || isTypeAssignableToKind(rightType, 134217728 | 7372800))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -37242,6 +37354,8 @@ var ts; error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; + default: + return ts.Debug.fail(); } function checkSpecialAssignment(left, right) { var special = ts.getSpecialPropertyAssignmentKind(left.parent); @@ -37326,7 +37440,9 @@ var ts; } } var func = ts.getContainingFunction(node); - var functionFlags = func ? ts.getFunctionFlags(func) : 0; + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); if (!(functionFlags & 1)) { return anyType; } @@ -37422,14 +37538,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 && - constraintDeclaration.operator === 128; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216) { @@ -37438,17 +37546,15 @@ var ts; } if (contextualType.flags & 7372800) { var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 | 64 | 1024) || - constraint.flags & 2 && maybeTypeOfKind(candidateType, 32) || - constraint.flags & 4 && maybeTypeOfKind(candidateType, 64) || - constraint.flags & 8 && maybeTypeOfKind(candidateType, 128) || - constraint.flags & 512 && maybeTypeOfKind(candidateType, 1024) || + return maybeTypeOfKind(constraint, 2) && maybeTypeOfKind(candidateType, 32) || + maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 64) || + maybeTypeOfKind(constraint, 512) && maybeTypeOfKind(candidateType, 1024) || isLiteralOfContextualType(candidateType, constraint); } - return contextualType.flags & (32 | 524288) && maybeTypeOfKind(candidateType, 32) || + return !!(contextualType.flags & (32 | 524288) && maybeTypeOfKind(candidateType, 32) || contextualType.flags & 64 && maybeTypeOfKind(candidateType, 64) || contextualType.flags & 128 && maybeTypeOfKind(candidateType, 128) || - contextualType.flags & 1024 && maybeTypeOfKind(candidateType, 1024); + contextualType.flags & 1024 && maybeTypeOfKind(candidateType, 1024)); } return false; } @@ -37834,20 +37940,21 @@ var ts; else { var isStatic = ts.hasModifier(member, 32); var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { switch (member.kind) { case 155: - addName(names, member.name, memberName, 1); + addName(names, name, memberName, 1); break; case 156: - addName(names, member.name, memberName, 2); + addName(names, name, memberName, 2); break; case 151: - addName(names, member.name, memberName, 3); + addName(names, name, memberName, 3); break; case 153: - addName(names, member.name, memberName, 4); + addName(names, name, memberName, 4); break; } } @@ -37900,13 +38007,14 @@ var ts; var member = _a[_i]; if (member.kind === 150) { var memberName = void 0; - switch (member.name.kind) { + var name = member.name; + switch (name.kind) { case 9: case 8: - memberName = member.name.text; + memberName = name.text; break; case 71: - memberName = ts.idText(member.name); + memberName = ts.idText(name); break; default: continue; @@ -38479,7 +38587,7 @@ var ts; case 247: return 1; default: - ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); } } } @@ -38563,7 +38671,8 @@ var ts; var thenFunction = getTypeOfPropertyOfType(type, "then"); if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); + if (!diagnosticMessage) + return ts.Debug.fail(); error(errorNode, diagnosticMessage); } return undefined; @@ -38638,11 +38747,11 @@ var ts; break; case 148: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; case 151: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 153: case 155: @@ -38651,6 +38760,8 @@ var ts; var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; + default: + return ts.Debug.fail(); } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } @@ -38935,13 +39046,6 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 231 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 147) { - return; - } - } var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(0, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } @@ -39014,6 +39118,7 @@ var ts; return; var unusedImports = ts.createMap(); var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); nodeWithLocals.locals.forEach(function (local) { if (local.flags & 262144 ? !(local.flags & 3 && !(local.isReferenced & 3)) : local.isReferenced || local.exportSymbol) { return; @@ -39031,6 +39136,11 @@ var ts; addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + if (!isIdentifierThatStartsWithUnderScore(declaration.name) || !ts.isForInOrOfStatement(declaration.parent.parent)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + } else { var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); if (parameter) { @@ -39048,47 +39158,74 @@ var ts; unusedImports.forEach(function (_a) { var importClause = _a[0], unuseds = _a[1]; var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 245 ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(0, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { var unused = unuseds_1[_i]; errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } } - else if (unuseds.length === 1) { - addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); - } - else { - addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); - } }); unusedDestructures.forEach(function (_a) { var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 : 0; - if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 231 && bindingPattern.parent.parent.kind === 232) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } } - else if (bindingElements.length === 1) { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(0, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 213 ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(0, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + } } }); } + function bindingNameText(name) { + switch (name.kind) { + case 71: + return ts.idText(name); + case 180: + case 179: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } function isImportedDeclaration(node) { return node.kind === 244 || node.kind === 247 || node.kind === 245; } function importClauseFromImported(decl) { return decl.kind === 244 ? decl : decl.kind === 245 ? decl.parent : decl.parent.parent; } - function forEachImportedDeclaration(importClause, cb) { - var defaultName = importClause.name, namedBindings = importClause.namedBindings; - return (defaultName && cb(importClause)) || - namedBindings && (namedBindings.kind === 245 ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); - } function checkBlock(node) { if (node.kind === 212) { checkGrammarStatementInAmbientContext(node); @@ -39148,6 +39285,7 @@ var ts; } return true; } + return false; }); } function checkIfNewTargetIsCapturedInEnclosingScope(node) { @@ -39162,6 +39300,7 @@ var ts; } return true; } + return false; }); } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -39502,7 +39641,7 @@ var ts; checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - if (rightType === neverType || !isTypeAssignableToKind(rightType, 134217728 | 7372800)) { + if (rightType === neverType || !(rightType.flags & 1 || isTypeAssignableToKind(rightType, 134217728 | 7372800))) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -39620,11 +39759,11 @@ var ts; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); if (isTypeAny(methodType)) { return undefined; } - var signatures = methodType && getSignaturesOfType(methodType, 0); + var signatures = methodType ? getSignaturesOfType(methodType, 0) : undefined; if (!ts.some(signatures)) { if (errorNode) { reportTypeNotIterableError(errorNode, type, allowAsyncIterables); @@ -39718,7 +39857,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 ? getPromisedTypeOfPromise(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 | 1); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 | 1); } function checkReturnStatement(node) { if (checkGrammarStatementInAmbientContext(node)) { @@ -39826,6 +39965,7 @@ var ts; grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } + return false; }); } checkSourceElement(node.statement); @@ -39881,8 +40021,8 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (ts.getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 && ts.isClassLike(classDeclaration)) { for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; if (!ts.hasModifier(member, 32) && hasNonBindableDynamicName(member)) { @@ -39983,8 +40123,8 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { var name = symbolToString(symbol); - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -39993,8 +40133,8 @@ var ts; function areTypeParametersIdentical(declarations, targetParameters) { var maxTypeArgumentCount = ts.length(targetParameters); var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); var numTypeParameters = sourceParameters.length; if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { @@ -40203,7 +40343,7 @@ var ts; if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if (isPrototypeProperty(base) && isPrototypeProperty(derived) || base.flags & 98308 && derived.flags & 98308) { + if (isPrototypeProperty(base) || base.flags & 98308 && derived.flags & 98308) { continue; } var errorMessage = void 0; @@ -40436,7 +40576,11 @@ var ts; case 190: return evaluate(expr.expression); case 71: - return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); case 185: case 184: var ex = expr; @@ -40527,8 +40671,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if ((declaration.kind === 234 || (declaration.kind === 233 && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304)) { @@ -40578,7 +40722,7 @@ var ts; if (symbol.flags & 512 && symbol.declarations.length > 1 && !inAmbientContext - && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -40692,7 +40836,7 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (ts.nodeIsMissing(moduleName)) { + if (!moduleName || ts.nodeIsMissing(moduleName)) { return false; } if (!ts.isStringLiteral(moduleName)) { @@ -40917,8 +41061,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -40940,11 +41084,11 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var tags = _a[_i].tags; - ts.forEach(tags, checkSourceElement); - } + if (ts.isInJavaScriptFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); } var kind = node.kind; if (cancellationToken) { @@ -41113,7 +41257,7 @@ var ts; if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } - var paramTag = parent.parent; + var paramTag = node.parent.parent; if (!ts.isJSDocParameterTag(paramTag)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); return; @@ -41130,8 +41274,8 @@ var ts; function getTypeFromJSDocVariadicType(node) { var type = getTypeFromTypeNode(node.type); var parent = node.parent; - var paramTag = parent.parent; - if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { var host_1 = ts.getHostSignatureFromJSDoc(paramTag); if (host_1) { var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); @@ -41153,8 +41297,8 @@ var ts; } } function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; + for (var _i = 0, _a = deferredNodes; _i < _a.length; _i++) { + var node = _a[_i]; switch (node.kind) { case 191: case 192: @@ -41181,9 +41325,9 @@ var ts; function unusedIsError(kind) { switch (kind) { case 0: - return compilerOptions.noUnusedLocals; + return !!compilerOptions.noUnusedLocals; case 1: - return compilerOptions.noUnusedParameters; + return !!compilerOptions.noUnusedParameters; default: return ts.Debug.assertNever(kind); } @@ -41341,21 +41485,21 @@ var ts; case 236: case 237: return true; + default: + return false; } } - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 145) { + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 145) { node = node.parent; } - return node.parent && node.parent.kind === 161; + return node.parent.kind === 161; } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 184) { + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 184) { node = node.parent; } - return node.parent && node.parent.kind === 206; + return node.parent.kind === 206; } function forEachEnclosingClass(node, callback) { var result; @@ -41387,10 +41531,10 @@ var ts; nodeOnRightSide = nodeOnRightSide.parent; } if (nodeOnRightSide.parent.kind === 242) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } if (nodeOnRightSide.parent.kind === 248) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; } @@ -41520,23 +41664,25 @@ var ts; if (node.kind === 273) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } + var parent = node.parent; + var grandParent = parent.parent; if (node.flags & 8388608) { return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { - return getSymbolOfNode(node.parent); + return getSymbolOfNode(parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); + return getSymbolOfNode(parent.parent); } if (node.kind === 71) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 181 && - node.parent.parent.kind === 179 && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); + else if (parent.kind === 181 && + grandParent.kind === 179 && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; @@ -41578,10 +41724,10 @@ var ts; return resolveExternalModuleName(node, node); } case 8: - var objectType = ts.isElementAccessExpression(node.parent) - ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined - : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) - ? getTypeFromTypeNode(node.parent.parent.objectType) + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79: @@ -41729,9 +41875,9 @@ var ts; } return target; } - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var isPropertyName_1 = node.parent.kind === 184 && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; @@ -41759,11 +41905,10 @@ var ts; } } function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); if (symbol) { @@ -41787,8 +41932,8 @@ var ts; } } } - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); if (isNonLocalAlias(symbol, 67216319)) { @@ -41822,9 +41967,9 @@ var ts; } return false; } - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { @@ -41834,8 +41979,8 @@ var ts; } return undefined; } - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); if (node) { var symbol = getSymbolOfNode(node); if (symbol) { @@ -41854,7 +41999,7 @@ var ts; return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 249: var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); case 248: return node.expression && node.expression.kind === 71 @@ -41863,8 +42008,8 @@ var ts; } return false; } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); if (node === undefined || node.parent.kind !== 273 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } @@ -41876,11 +42021,11 @@ var ts; if (target === unknownSymbol) { return true; } - return target.flags & 67216319 && + return !!(target.flags & 67216319) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { if (ts.isAliasSymbolDeclaration(node)) { @@ -41894,7 +42039,7 @@ var ts; } } if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); } return false; } @@ -41910,10 +42055,10 @@ var ts; return false; } function isRequiredInitializedParameter(parameter) { - return strictNullChecks && + return !!strictNullChecks && !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && - parameter.initializer && + !!parameter.initializer && !ts.hasModifier(parameter, 92); } function isOptionalUninitializedParameterProperty(parameter) { @@ -41923,7 +42068,7 @@ var ts; ts.hasModifier(parameter, 92); } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + return getNodeLinks(node).flags || 0; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -41951,10 +42096,10 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 65536 && getSignaturesOfType(type, 0).length > 0; + return !!(type.flags & 65536) && getSignaturesOfType(type, 0).length > 0; } - function getTypeReferenceSerializationKind(typeName, location) { - typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + function getTypeReferenceSerializationKind(typeNameIn, location) { + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); if (!typeName) return ts.TypeReferenceSerializationKind.Unknown; if (location) { @@ -41975,7 +42120,7 @@ var ts; } } if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -42012,8 +42157,8 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { - declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { return ts.createToken(119); } @@ -42030,16 +42175,16 @@ var ts; } return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024, tracker); } - function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { - signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { return ts.createToken(119); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, tracker); } - function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { - expr = ts.getParseTreeNode(expr, ts.isExpression); + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { return ts.createToken(119); } @@ -42063,9 +42208,9 @@ var ts; } return resolveName(location, reference.escapedText, 67216319 | 1048576 | 2097152, undefined, undefined, true); } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); if (reference) { var symbol = getReferencedValueSymbol(reference); if (symbol) { @@ -42118,7 +42263,7 @@ var ts; }, getNodeCheckFlags: function (node) { node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; + return node ? getNodeCheckFlags(node) : 0; }, isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, @@ -42131,8 +42276,8 @@ var ts; createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, collectLinkedAliases: collectLinkedAliases, @@ -42145,8 +42290,8 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - isLateBound: function (node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024); }, @@ -42347,7 +42492,7 @@ var ts; case 16384: return "__asyncValues"; case 32768: return "__exportStar"; case 65536: return "__makeTemplateObject"; - default: ts.Debug.fail("Unrecognized helper"); + default: return ts.Debug.fail("Unrecognized helper"); } } function resolveHelpersModule(node, errorNode) { @@ -42561,7 +42706,7 @@ var ts; else if (flags & 64) { return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); } - return; + return false; } else if ((node.kind === 243 || node.kind === 242) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); @@ -42575,6 +42720,7 @@ var ts; if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); } + return false; } function reportObviousModifierErrors(node) { return !node.modifiers @@ -42641,6 +42787,7 @@ var ts; if (list && list.hasTrailingComma) { return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); } + return false; } function checkGrammarTypeParameterList(typeParameters, file) { if (typeParameters && typeParameters.length === 0) { @@ -42648,6 +42795,7 @@ var ts; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); } + return false; } function checkGrammarParameterList(parameters) { var seenOptionalParameter = false; @@ -42738,6 +42886,7 @@ var ts; if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } + return false; } function checkGrammarIndexSignature(node) { return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); @@ -42749,6 +42898,7 @@ var ts; var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); } + return false; } function checkGrammarTypeArguments(node, typeArguments) { return checkGrammarForDisallowedTrailingComma(typeArguments) || @@ -42763,6 +42913,7 @@ var ts; } } } + return false; } function checkGrammarArguments(args) { return checkGrammarForOmittedArgument(args); @@ -42776,7 +42927,7 @@ var ts; var listType = ts.tokenToString(node.token); return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } - return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + return ts.some(types, checkGrammarExpressionWithTypeArguments); } function checkGrammarExpressionWithTypeArguments(node) { return checkGrammarTypeArguments(node, node.typeArguments); @@ -42838,6 +42989,7 @@ var ts; if (computedPropertyName.expression.kind === 199 && computedPropertyName.expression.operatorToken.kind === 26) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } + return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { @@ -42853,9 +43005,7 @@ var ts; } } function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } + return !!questionToken && grammarErrorOnNode(questionToken, message); } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var seen = ts.createUnderscoreEscapedMap(); @@ -42897,7 +43047,7 @@ var ts; currentKind = 4; break; default: - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -43023,6 +43173,7 @@ var ts; } } } + return false; } function doesAccessorHaveCorrectParameterCount(accessor) { return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 155 ? 0 : 1); @@ -43226,6 +43377,7 @@ var ts; } } } + return false; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 71) { @@ -43242,6 +43394,7 @@ var ts; } } } + return false; } function checkGrammarVariableDeclarationList(declarationList) { var declarations = declarationList.declarations; @@ -43251,6 +43404,7 @@ var ts; if (!declarationList.declarations.length) { return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } + return false; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { @@ -43302,6 +43456,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); @@ -43309,6 +43464,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorOnNode(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -43316,6 +43472,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; } + return false; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); @@ -43382,6 +43539,7 @@ var ts; } } } + return false; } function checkGrammarSourceFile(node) { return !!(node.flags & 4194304) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); @@ -43404,6 +43562,7 @@ var ts; else { } } + return false; } function checkGrammarNumericLiteral(node) { if (node.numericLiteralFlags & 32) { @@ -43423,6 +43582,7 @@ var ts; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } + return false; } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -43431,6 +43591,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), 0, message, arg0, arg1, arg2)); return true; } + return false; } function getAmbientModules() { if (!ambientModulesCache) { @@ -43457,6 +43618,7 @@ var ts; if (ts.isSpreadElement(nodeArguments[0])) { return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); } + return false; } } ts.createTypeChecker = createTypeChecker; @@ -43526,7 +43688,7 @@ var ts; ts.createNodeArray = createNodeArray; function getSynthesizedClone(node) { if (node === undefined) { - return undefined; + return node; } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; @@ -45038,6 +45200,7 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0; } var node = createSynthesizedNode(232); node.flags |= flags & 3; node.declarations = createNodeArray(declarations); @@ -45159,6 +45322,7 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0; } var node = createSynthesizedNode(238); node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); @@ -45654,6 +45818,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -46272,7 +46438,7 @@ var ts; ts.createSpreadHelper = createSpreadHelper; function createForOfBindingStatement(node, boundValue) { if (ts.isVariableDeclarationList(node)) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); + var firstDeclaration = ts.first(node.declarations); var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, undefined, boundValue); return ts.setTextRange(ts.createVariableStatement(undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), node); } @@ -46326,6 +46492,7 @@ var ts; } } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } var callee = skipOuterExpressions(expression, 7); var thisArg; var target; @@ -46412,7 +46579,7 @@ var ts; switch (property.kind) { case 155: case 156: - return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); case 269: return createExpressionForPropertyAssignment(property, receiver); case 270: @@ -46489,6 +46656,7 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { var name = ts.getMutableClone(nodeName); @@ -46513,7 +46681,7 @@ var ts; function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); ts.setTextRange(qualifiedName, name); - var emitFlags; + var emitFlags = 0; if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -46528,7 +46696,8 @@ var ts; } ts.convertToFunctionBody = convertToFunctionBody; function convertFunctionDeclarationToExpression(node) { - ts.Debug.assert(!!node.body); + if (!node.body) + return ts.Debug.fail(); var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); @@ -46573,7 +46742,7 @@ var ts; ts.addStandardPrologue = addStandardPrologue; function addCustomPrologue(target, source, statementOffset, visitor) { var numStatements = source.length; - while (statementOffset < numStatements) { + while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); @@ -47025,8 +47194,9 @@ var ts; return bindingElement.initializer; } if (ts.isPropertyAssignment(bindingElement)) { - return ts.isAssignmentExpression(bindingElement.initializer, true) - ? bindingElement.initializer.right + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, true) + ? initializer.right : undefined; } if (ts.isShorthandPropertyAssignment(bindingElement)) { @@ -47961,7 +48131,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function liftToBlock(nodes) { @@ -48089,7 +48259,7 @@ var ts; return ts.some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { - return e.propertyName && e.propertyName.escapedText === "default"; + return e.propertyName !== undefined && e.propertyName.escapedText === "default"; } function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; @@ -48122,7 +48292,7 @@ var ts; } ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { - return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -48307,7 +48477,7 @@ var ts; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: true, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -48372,13 +48542,14 @@ var ts; return false; } function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } var pendingExpressions; var pendingDeclarations = []; var declarations = []; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: hoistTempVariables, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -48404,7 +48575,7 @@ var ts; } else { context.hoistVariableDeclaration(temp); - var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + var pendingDeclaration = ts.last(pendingDeclarations); pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); pendingDeclaration.value = temp; @@ -48986,7 +49157,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ @@ -49576,7 +49747,8 @@ var ts; return serializedUnion || ts.createVoidZero(); } function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -49602,8 +49774,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } function serializeEntityNameAsExpression(node, useFallback) { @@ -49872,7 +50045,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); @@ -49902,7 +50075,7 @@ var ts; } } function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } function hasNamespaceQualifiedExportName(node) { return isExportOfNamespace(node) @@ -50017,7 +50190,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -50471,8 +50644,9 @@ var ts; : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } function visitForStatementInAsyncBody(node) { - return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) - ? visitVariableDeclarationListWithCollidingNames(node.initializer, false) + var initializer = node.initializer; + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, false) : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } function visitAwaitExpression(node) { @@ -50513,10 +50687,10 @@ var ts; } } function isVariableDeclarationListWithCollidingName(node) { - return node + return !!node && ts.isVariableDeclarationList(node) && !(node.flags & 3) - && ts.forEach(node.declarations, collidesWithParameterName); + && node.declarations.some(collidesWithParameterName); } function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { hoistVariableDeclarationList(node); @@ -50583,7 +50757,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); if (languageVersion >= 2) { @@ -51090,7 +51264,7 @@ var ts; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { @@ -51116,7 +51290,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -51841,7 +52015,7 @@ var ts; hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return hierarchyFacts & 4096 + return (hierarchyFacts & 4096) !== 0 && node.kind === 224 && !node.expression; } @@ -51981,7 +52155,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0, 0); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -52050,7 +52224,8 @@ var ts; (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; - if (!node.label) { + var label = node.label; + if (!label) { if (node.kind === 223) { convertedLoopState.nonLocalJumps |= 2; labelMarker = "break"; @@ -52062,12 +52237,12 @@ var ts; } else { if (node.kind === 223) { - labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, true, ts.idText(node.label), labelMarker); + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, true, ts.idText(label), labelMarker); } else { - labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, false, ts.idText(node.label), labelMarker); + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, false, ts.idText(label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -52150,7 +52325,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); ts.setEmitFlags(block, 1536); return block; @@ -52176,7 +52351,7 @@ var ts; convertedLoopState = savedConvertedLoopState; } function transformConstructorParameters(constructor, hasSynthesizedSuper) { - return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { @@ -52197,7 +52372,7 @@ var ts; } ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); } - var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); if (superCaptureStatus === 1 || superCaptureStatus === 2) { statementOffset++; @@ -52213,7 +52388,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, false); } @@ -52615,7 +52790,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, false); if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { multiLine = true; @@ -52718,11 +52893,10 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 - && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); if (firstDeclaration) { - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); } } return declarationList; @@ -52817,35 +52991,34 @@ var ts; } function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { var statements = []; - if (ts.isVariableDeclarationList(node.initializer)) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { if (node.initializer.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } - var firstOriginalDeclaration = ts.firstOrUndefined(node.initializer.declarations); + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0, boundValue); var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer); ts.setOriginalNode(declarationList, node.initializer); - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { statements.push(ts.setTextRange(ts.createVariableStatement(undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, boundValue) - ]), ts.moveRangePos(node.initializer, -1)), node.initializer)), ts.moveRangeEnd(node.initializer, -1))); + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); } } else { - var assignment = ts.createAssignment(node.initializer, boundValue); + var assignment = ts.createAssignment(initializer, boundValue); if (ts.isDestructuringAssignment(assignment)) { ts.aggregateTransformFlags(assignment); statements.push(ts.createStatement(visitBinaryExpression(assignment, false))); } else { - assignment.end = node.initializer.end; - statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); } } if (convertedLoopBodyStatements) { @@ -53020,7 +53193,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, true); } if (ts.isBlock(loopBody)) { @@ -53214,7 +53387,7 @@ var ts; case 156: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; case 153: @@ -53322,7 +53495,7 @@ var ts; } function visitArrayLiteralExpression(node) { if (node.transformFlags & 64) { - return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); + return transformAndSpreadElements(node.elements, true, !!node.multiLine, !!node.elements.hasTrailingComma); } return ts.visitEachChild(node, visitor, context); } @@ -53337,11 +53510,11 @@ var ts; } function visitTypeScriptClassWrapper(node) { var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); - var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); - var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); var variable = varStatement.declarationList.declarations[0]; var initializer = ts.skipOuterExpressions(variable.initializer); var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); @@ -53604,14 +53777,13 @@ var ts; return node; } function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { + switch (node.parent.kind) { case 181: case 234: case 237: case 231: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); } return false; } @@ -53779,7 +53951,7 @@ var ts; } function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token >= 72 && token <= 107) { + if (token !== undefined && token >= 72 && token <= 107) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -53796,6 +53968,7 @@ var ts; case 4: return "yield"; case 5: return "yield*"; case 7: return "endfinally"; + default: return undefined; } } function transformGenerators(context) { @@ -54014,7 +54187,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); inGeneratorFunctionBody = savedInGeneratorFunctionBody; inStatementContainingYield = savedInStatementContainingYield; @@ -54052,13 +54225,14 @@ var ts; } } function visitBinaryExpression(node) { - switch (ts.getExpressionAssociativity(node)) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { case 0: return visitLeftAssociativeBinaryExpression(node); case 1: return visitRightAssociativeBinaryExpression(node); default: - ts.Debug.fail("Unknown associativity."); + return ts.Debug.assertNever(assoc); } } function isCompoundAssignment(kind) { @@ -54712,7 +54886,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 16777216) !== 0; + return !!node && (node.transformFlags & 16777216) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -54799,7 +54973,8 @@ var ts; } function endBlock() { var block = peekBlock(); - ts.Debug.assert(block !== undefined, "beginBlock was never called."); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); var index = blockActions.length; blockActions[index] = 1; blockOffsets[index] = operations ? operations.length : 0; @@ -55042,7 +55217,7 @@ var ts; return 0; } function createLabel(label) { - if (label > 0) { + if (label !== undefined && label > 0) { if (labelExpressions === undefined) { labelExpressions = []; } @@ -55480,7 +55655,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); @@ -55595,7 +55770,7 @@ var ts; } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); @@ -56399,7 +56574,7 @@ var ts; ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); ts.addRange(statements, hoistedStatements); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -56857,7 +57032,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -56880,9 +57055,6 @@ var ts; && shouldHoistVariableDeclarationList(node); } function visitForInitializer(node) { - if (!node) { - return node; - } if (shouldHoistForInitializer(node)) { var expressions = void 0; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { @@ -57356,7 +57528,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 231 || node.kind === 181) { @@ -57481,7 +57653,7 @@ var ts; ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; break; default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); } return { diagnosticMessage: diagnosticMessage, @@ -57546,7 +57718,7 @@ var ts; ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; default: - ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); } } function getTypeParameterConstraintVisibilityError() { @@ -57583,7 +57755,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } return { diagnosticMessage: diagnosticMessage, @@ -57742,7 +57914,7 @@ var ts; var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) - return; + return undefined; hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -57963,7 +58135,7 @@ var ts; return false; } if (ts.isBindingPattern(elem.name)) { - return ts.forEach(elem.name.elements, getBindingNameVisible); + return ts.some(elem.name.elements, getBindingNameVisible); } else { return resolver.isDeclarationVisible(elem); @@ -58005,7 +58177,7 @@ var ts; } function rewriteModuleSpecifier(parent, input) { if (!input) - return; + return undefined; resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 238 && parent.kind !== 178); if (input.kind === 9 && isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -59022,7 +59194,7 @@ var ts; } if (node) { var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var range = emitNode && emitNode.sourceMapRange; var _a = range || node, pos = _a.pos, end = _a.end; var source = range && range.source; @@ -59062,7 +59234,7 @@ var ts; return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128) === 0 && tokenPos >= 0) { @@ -59096,7 +59268,7 @@ var ts; } function getText() { if (disabled) { - return; + return undefined; } encodeLastRecordedSourceMapSpan(); return JSON.stringify({ @@ -59111,7 +59283,7 @@ var ts; } function getSourceMappingURL() { if (disabled) { - return; + return undefined; } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.base64encode(ts.sys, getText()); @@ -59163,7 +59335,7 @@ var ts; var currentLineMap; var detachedCommentsInfo; var hasWrittenComment = false; - var disabled = printerOptions.removeComments; + var disabled = !!printerOptions.removeComments; return { reset: reset, setWriter: setWriter, @@ -59181,7 +59353,7 @@ var ts; if (node) { hasWrittenComment = false; var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; if ((pos < 0 && end < 0) || (pos === end)) { emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); @@ -59445,10 +59617,10 @@ var ts; detachedCommentsInfo = undefined; } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { - var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -59488,6 +59660,7 @@ var ts; var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { @@ -59517,7 +59690,7 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { @@ -59579,7 +59752,7 @@ var ts; emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, - sourceMaps: sourceMapDataList + sourceMaps: sourceMapDataList, }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -59672,7 +59845,7 @@ var ts; if (sourceMapFilePath) { ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), false, sourceFiles); } - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); if (bundleInfoPath) { bundleInfo.totalLength = writer.getTextPos(); ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), false); @@ -59901,8 +60074,7 @@ var ts; return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode); - onEmitNode(hint, node, getNextPipelinePhase(0, hint)); + ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0, hint)); } function pipelineEmitWithComments(hint, node) { ts.Debug.assertDefined(emitNodeWithComments); @@ -59914,9 +60086,8 @@ var ts; pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assertDefined(onEmitSourceMapOfNode); ts.Debug.assert(hint !== 0 && hint !== 2); - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); + ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { if (hint === 0) @@ -61546,7 +61717,7 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) @@ -61790,7 +61961,7 @@ var ts; if (isUndefined && format & 8192) { return; } - var isEmpty = isUndefined || start >= children.length || count === 0; + var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 16384) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -61831,7 +62002,7 @@ var ts; increaseIndent(); } var previousSibling = void 0; - var shouldDecreaseIndentAfterEmit = void 0; + var shouldDecreaseIndentAfterEmit = false; for (var i = 0; i < count; i++) { var child = children[start + i]; if (previousSibling) { @@ -62417,7 +62588,7 @@ var ts; case 3: return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16), !!(name.autoGenerateFlags & 8)); } - ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } function getNodeForGeneratedName(name) { var autoGenerateId = name.autoGenerateId; @@ -63078,8 +63249,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -63107,7 +63277,7 @@ var ts; function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; - var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; + var oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -63124,7 +63294,7 @@ var ts; var modulesWithElidedImports = ts.createMap(); var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); - host = host || createCompilerHost(options); + var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); @@ -63601,7 +63771,7 @@ var ts; return nodes; } function isSourceFileFromExternalLibrary(file) { - return sourceFilesFoundSearchingNodeModules.get(file.path); + return !!sourceFilesFoundSearchingNodeModules.get(file.path); } function isSourceFileDefaultLibrary(file) { if (file.hasNoDefaultLib) { @@ -63615,7 +63785,7 @@ var ts; return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } } function getDiagnosticsProducingTypeChecker() { @@ -63732,11 +63902,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } function shouldReportDiagnostic(diagnostic) { @@ -64624,9 +64802,9 @@ var ts; if (ts.isObjectLiteralExpression(pathProp.initializer)) { for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { var keyProps = _b[_a]; - if (ts.isArrayLiteralExpression(keyProps.initializer) && - keyProps.initializer.elements.length > valueIndex) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); needCompilerDiagnostic = false; } } @@ -64728,6 +64906,7 @@ var ts; return false; } programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + return false; } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); @@ -64745,13 +64924,16 @@ var ts; if (out) { return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts"); } + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { var filePathWithoutExtension = ts.removeFileExtension(filePath); - return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts")) || - !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx")); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts")) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx")); } return false; } @@ -64879,7 +65061,7 @@ var ts; for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var version_1 = sourceFile.version; - var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -64926,7 +65108,8 @@ var ts; return false; } var info = state.fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); + if (!info) + return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { @@ -65051,7 +65234,7 @@ var ts; var ts; (function (ts) { function hasSameKeys(map1, map2) { - return map1 === map2 || map1 && map2 && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); } function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); @@ -65073,7 +65256,7 @@ var ts; ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); } var referencedMap = state.referencedMap; - var oldReferencedMap = useOldState && oldState.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -65239,7 +65422,7 @@ var ts; assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); if (!targetSourceFile) { var sourceMaps = []; - var emitSkipped = void 0; + var emitSkipped = false; var diagnostics = void 0; var emittedFiles = []; var affectedEmitResult = void 0; @@ -65350,7 +65533,7 @@ var ts; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); - var rootPath = rootDir && resolutionHost.toPath(rootDir); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); var typeRootsWatches = ts.createMap(); return { startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, @@ -65402,7 +65585,7 @@ var ts; return false; } var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); - return value && !!value.length; + return !!value && !!value.length; } function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { @@ -65411,7 +65594,7 @@ var ts; } var collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = undefined; - return function (path) { return (collected && collected.has(path)) || + return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { @@ -65744,7 +65927,7 @@ var ts; removeResolutionsOfFile(filePath); invalidateResolutions(function (resolution, getResolutionWithResolvedFileName) { var result = getResolutionWithResolvedFileName(resolution); - return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; }); } function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { @@ -65791,7 +65974,7 @@ var ts; return rootPath; } var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { @@ -66013,9 +66196,9 @@ var ts; system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { - reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); - var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; return host; @@ -66059,7 +66242,7 @@ var ts; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; - var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } @@ -66109,7 +66292,7 @@ var ts; readFile: readFile, trace: trace, directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), realpath: host.realpath && (function (s) { return host.realpath(s); }), getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), onReleaseOldSourceFile: onReleaseOldSourceFile, @@ -66735,6 +66918,13 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, + { + name: "strictAny", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_any_type + }, { name: "strictNullChecks", type: "boolean", @@ -67219,7 +67409,7 @@ var ts; case "string": return ts.map(values, function (v) { return v || ""; }); default: - return ts.filter(ts.map(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }), function (v) { return !!v; }); + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); } } ts.parseListTypeOption = parseListTypeOption; @@ -67598,6 +67788,7 @@ var ts; var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } + return false; } function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); @@ -68019,13 +68210,10 @@ var ts; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return undefined; + return false; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; + return typeof result === "boolean" && result; } function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; @@ -68054,7 +68242,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -68382,7 +68570,7 @@ var ts; } if (commandLine.options.help || commandLine.options.all) { printVersion(); - printHelp(commandLine.options.all); + printHelp(!!commandLine.options.all); return ts.sys.exit(ts.ExitStatus.Success); } if (commandLine.options.project) { @@ -68412,7 +68600,7 @@ var ts; } if (commandLine.fileNames.length === 0 && !configFileName) { printVersion(); - printHelp(commandLine.options.all); + printHelp(!!commandLine.options.all); return ts.sys.exit(ts.ExitStatus.Success); } var commandLineOptions = commandLine.options; @@ -68575,7 +68763,7 @@ var ts; output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); var optsList = showAllOptions ? ts.sort(ts.optionDeclarations, function (a, b) { return ts.compareStringsCaseInsensitive(a.name, b.name); }) : - ts.filter(ts.optionDeclarations.slice(), function (v) { return v.showInSimplifiedHelpView; }); + ts.filter(ts.optionDeclarations.slice(), function (v) { return !!v.showInSimplifiedHelpView; }); marginLength = 0; var usageColumn = []; var descriptionColumn = []; diff --git a/lib/tsserver.js b/lib/tsserver.js index dc5875cc4b9..655de4d0e34 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1154,6 +1154,7 @@ var ts; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; @@ -1386,7 +1387,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.9"; + ts.versionMajorMinor = "3.0"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { @@ -1657,7 +1658,7 @@ var ts; return result; } } - Debug.fail(); + return Debug.fail(); } ts.findMap = findMap; function contains(array, value, equalityComparer) { @@ -2187,15 +2188,6 @@ var ts; return to; } ts.addRange = addRange; - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; function pushIfUnique(array, toAdd, equalityComparer) { if (contains(array, toAdd, equalityComparer)) { return false; @@ -2588,10 +2580,10 @@ var ts; if (value !== undefined && test(value)) return value; if (value && typeof value.kind === "number") { - Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); } else { - Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } } ts.cast = cast; @@ -2671,7 +2663,7 @@ var ts; } ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { - baseIndex = baseIndex || 0; + if (baseIndex === void 0) { baseIndex = 0; } return text.replace(/{(\d+)}/g, function (_match, index) { return Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; @@ -2908,7 +2900,9 @@ var ts; return compareValues(a ? 1 : 0, b ? 1 : 0); } ts.compareBooleans = compareBooleans; - function compareMessageText(text1, text2) { + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; while (text1 && text2) { var string1 = isString(text1) ? text1 : text1.messageText; var string2 = isString(text2) ? text2 : text2.messageText; @@ -2942,6 +2936,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -2960,7 +2962,7 @@ var ts; } ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { - return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { @@ -3420,7 +3422,7 @@ var ts; var subpattern = ""; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); - var lastComponent = lastOrUndefined(components); + var lastComponent = last(components); if (usage !== "exclude" && lastComponent === "**") { return undefined; } @@ -3611,11 +3613,11 @@ var ts; return scriptKind === 1 || scriptKind === 2; } function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { @@ -3803,7 +3805,8 @@ var ts; } Debug.fail = fail; function assertDefined(value, message) { - assert(value !== undefined && value !== null, message); + if (value === undefined || value === null) + return fail(message); return value; } Debug.assertDefined = assertDefined; @@ -3961,10 +3964,7 @@ var ts; ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); - if (ext !== undefined) { - return ext; - } - Debug.fail("File " + path + " has unknown extension."); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; function isAnySupportedFileExtension(path) { @@ -4518,6 +4518,7 @@ var ts; return watchDirectoryRecursively(directoryName, callback); } watchDirectory(directoryName, callback); + return undefined; }; } function createNonPollingWatchFile() { @@ -4748,6 +4749,7 @@ var ts; switch (entryKind) { case 0: return stat.isFile(); case 1: return stat.isDirectory(); + default: return false; } } catch (e) { @@ -5430,7 +5432,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -5758,6 +5760,8 @@ var ts; _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true), Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", true), + Enable_strict_checking_of_any_type: diag(6200, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_any_type_6200", "Enable strict checking of 'any' type."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5785,7 +5789,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -5866,6 +5870,7 @@ var ts; Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5935,6 +5940,7 @@ var ts; Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), }; })(ts || (ts = {})); var ts; @@ -6526,8 +6532,9 @@ var ts; return true; } ts.isIdentifierText = isIdentifierText; - function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } + var text = textInitial; var pos; var end; var startPos; @@ -7725,7 +7732,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function packageIdToString(_a) { var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; @@ -7832,6 +7839,19 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { if (text.charCodeAt(commentPos + 1) === 47 && commentPos + 2 < commentEnd && @@ -7901,7 +7921,7 @@ var ts; ts.indexOfNode = indexOfNode; function getEmitFlags(node) { var emitNode = node.emitNode; - return emitNode && emitNode.flags; + return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { @@ -7929,7 +7949,7 @@ var ts; case 12: return node.text; } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { @@ -8023,7 +8043,7 @@ var ts; case 192: return true; case 212: - return parentNode && !ts.isFunctionLike(parentNode); + return !ts.isFunctionLike(parentNode); } return false; } @@ -8124,6 +8144,8 @@ var ts; return entityNameToString(name.left) + "." + entityNameToString(name.right); case 184: return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); } } ts.entityNameToString = entityNameToString; @@ -8318,7 +8340,7 @@ var ts; ts.Debug.assert(node.kind === 71 || node.kind === 145 || node.kind === 184, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 145: case 184: - case 99: + case 99: { var parent = node.parent; if (parent.kind === 164) { return false; @@ -8360,6 +8382,7 @@ var ts; case 188: return false; } + } } return false; } @@ -8540,15 +8563,16 @@ var ts; return ts.filter(objectLiteral.properties, function (property) { if (property.kind === 269) { var propName = getTextOfPropertyName(property.name); - return key === propName || (key2 && key2 === propName); + return key === propName || (!!key2 && key2 === propName); } + return false; }); } ts.getPropertyAssignment = getPropertyAssignment; function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { var expression = tsConfigSourceFile.statements[0].expression; - return ts.isObjectLiteralExpression(expression) && expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); } } ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; @@ -8571,10 +8595,11 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 273); while (true) { node = node.parent; if (!node) { - return undefined; + return ts.Debug.fail(); } switch (node.kind) { case 146: @@ -8750,10 +8775,12 @@ var ts; function childIsDecorated(node, parent) { switch (node.kind) { case 234: - return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); case 153: case 156: - return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + default: + return false; } } ts.childIsDecorated = childIsDecorated; @@ -8896,15 +8923,15 @@ var ts; } ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536); + return !!node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; function isInJsonFile(node) { - return node && !!(node.flags & 16777216); + return !!node && !!(node.flags & 16777216); } ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { - return node && !!(node.flags & 2097152); + return !!node && !!(node.flags & 2097152); } ts.isInJSDoc = isInJSDoc; function isJSDocIndexSignature(node) { @@ -9128,7 +9155,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 243 && node.importClause && !!node.importClause.name; + return node.kind === 243 && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { @@ -9165,16 +9192,18 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 && - node.expression.right; + node.expression.operatorToken.kind === 58 + ? node.expression.right + : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && getSpecialPropertyAssignmentKind(node.expression) !== 0 && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 && - node.expression.right.right; + node.expression.right.operatorToken.kind === 54 + ? node.expression.right.right + : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { @@ -9188,15 +9217,14 @@ var ts; } } function getSingleVariableOfVariableStatement(node) { - return ts.isVariableStatement(node) && - node.declarationList.declarations.length > 0 && - node.declarationList.declarations[0]; + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } function getNestedModuleDeclaration(node) { - return node.kind === 238 && + return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 238 && - node.body; + node.body.kind === 238 + ? node.body + : undefined; } function getJSDocCommentsAndTags(hostNode) { var result; @@ -9277,12 +9305,12 @@ var ts; ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { var last = ts.lastOrUndefined(s.parameters); - return last && isRestParameter(last); + return !!last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || type && type.kind === 284; + return node.dotDotDotToken !== undefined || !!type && type.kind === 284; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9409,9 +9437,10 @@ var ts; switch (name.kind) { case 71: case 9: - case 8: - if (ts.isDeclaration(name.parent)) { - return name.parent.name === name; + case 8: { + var parent = name.parent; + if (ts.isDeclaration(parent)) { + return parent.name === name; } else if (ts.isQualifiedName(name.parent)) { var tag = name.parent.parent; @@ -9421,6 +9450,7 @@ var ts; var binExp = name.parent.parent; return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; } + } default: return false; } @@ -9603,7 +9633,7 @@ var ts; ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); - return name && isDynamicName(name); + return !!name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -10035,7 +10065,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); + linePos = output.length - s.length + ts.last(lineStartsOfS); } } } @@ -10194,7 +10224,7 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return node && node.kind === 71 && identifierIsThisKeyword(node); + return !!node && node.kind === 71 && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { @@ -10363,12 +10393,12 @@ var ts; lastComment = comment; } if (detachedComments.length) { - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; } } } @@ -10511,7 +10541,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 206 && + if (ts.isExpressionWithTypeArguments(node) && node.parent.token === 85 && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -11292,7 +11322,7 @@ var ts; try { ts.localizedDiagnosticMessages = JSON.parse(fileContents); } - catch (e) { + catch (_a) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); } @@ -12850,7 +12880,8 @@ var ts; } ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { - return !!node.jsDoc && node.jsDoc.length > 0; + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; function hasType(node) { @@ -13475,6 +13506,7 @@ var ts; } ts.isExternalModule = isExternalModule; function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); newSourceFile.flags |= (sourceFile.flags & 1572864); return newSourceFile; @@ -13512,6 +13544,7 @@ var ts; var contextFlags; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); @@ -13693,6 +13726,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -14120,7 +14154,7 @@ var ts; case 14: return true; } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17); @@ -14196,6 +14230,8 @@ var ts; return token() === 29 || token() === 41; case 14: return token() === 27 && lookAhead(nextTokenIsSlash); + default: + return false; } } function isVariableDeclaratorListTerminator() { @@ -14440,6 +14476,7 @@ var ts; case 22: return ts.Diagnostics.Identifier_expected; case 13: return ts.Diagnostics.Identifier_expected; case 14: return ts.Diagnostics.Identifier_expected; + default: return undefined; } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -14530,7 +14567,7 @@ var ts; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(list).literal.kind === 15); + } while (ts.last(list).literal.kind === 15); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } @@ -14838,7 +14875,7 @@ var ts; if (token() === 19 || token() === 27) { return true; } - var idToken; + var idToken = false; while (ts.isModifierKind(token())) { idToken = true; nextToken(); @@ -16837,6 +16874,7 @@ var ts; missing.modifiers = node.modifiers; return finishNode(missing); } + return undefined; } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { @@ -17127,7 +17165,7 @@ var ts; node.name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(node); } - ts.Debug.fail("Should not have attempted to parse class member declaration."); + return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 204); @@ -17166,14 +17204,12 @@ var ts; } function parseHeritageClause() { var tok = token(); - if (tok === 85 || tok === 108) { - var node = createNode(267); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; + ts.Debug.assert(tok === 85 || tok === 108); + var node = createNode(267); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); + return finishNode(node); } function parseExpressionWithTypeArguments() { var node = createNode(206); @@ -17559,8 +17595,8 @@ var ts; PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } var content = sourceText; - start = start || 0; var end = length === undefined ? content.length : start + length; length = end - start; ts.Debug.assert(start >= 0); @@ -17863,7 +17899,7 @@ var ts; var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target); + var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -18576,10 +18612,7 @@ var ts; break; } case "amd-dependency": { - context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { - var _b = _a.arguments, name = _b.name, path = _b.path; - return ({ name: name, path: path }); - }); + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); break; } case "amd-module": { @@ -19614,6 +19647,7 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -19655,7 +19689,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217) { addAntecedent(postStatementLabel, currentFlow); @@ -20201,6 +20235,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -20674,7 +20718,8 @@ var ts; } else { var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); - ts.Debug.assert(!!s && !!s.exports); + if (!s || !s.exports) + return ts.Debug.fail(); return action(e.name, s.exports.get(e.name.escapedText)); } } @@ -20819,7 +20864,7 @@ var ts; } function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); + return instanceState === 1 || (instanceState === 2 && !!options.preserveConstEnums); } function checkUnreachable(node) { if (!(currentFlow.flags & 1)) { @@ -20832,13 +20877,13 @@ var ts; (node.kind === 237 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304) && - (node.kind !== 213 || - ts.getCombinedNodeFlags(node.declarationList) & 3 || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -20853,8 +20898,8 @@ var ts; ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { return isExportsOrModuleExportsOrAlias(sourceFile, node) || @@ -21695,11 +21740,11 @@ var ts; } function visitSymbol(symbol) { if (!symbol) { - return; + return false; } var symbolId = ts.getSymbolId(symbol); if (visitedSymbols[symbolId]) { - return; + return false; } visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { @@ -21717,6 +21762,7 @@ var ts; visitSymbol(entity); } }); + return false; } } } @@ -21729,7 +21775,7 @@ var ts; } ts.trace = trace; function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; + return !!compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; function withPackageId(packageId, r) { @@ -21890,14 +21936,13 @@ var ts; } } function secondaryLookup() { - var resolvedFile; var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); + var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -22049,7 +22094,7 @@ var ts; result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; default: - ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -22227,7 +22272,7 @@ var ts; var originalPath = void 0; if (!compilerOptions.preserveSymlinks && resolvedValue) { originalPath = resolvedValue.path; - var path = realPath(resolved_1.value.path, host, traceEnabled); + var path = realPath(resolvedValue.path, host, traceEnabled); if (path === originalPath) { originalPath = undefined; } @@ -22327,7 +22372,7 @@ var ts; function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json"); - return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); } var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -22361,7 +22406,7 @@ var ts; } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, ext: ext }; + return path === undefined ? undefined : { path: path, ext: ext }; } } function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { @@ -22708,6 +22753,7 @@ var ts; var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var strictAny = ts.getStrictOptionValue(compilerOptions, "strictAny"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; @@ -22734,9 +22780,10 @@ var ts; location = ts.getParseTreeNode(location); return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); }, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, @@ -22748,8 +22795,8 @@ var ts; getBaseTypes: getBaseTypes, getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node ? getTypeFromTypeNode(node) : unknownType; }, getParameterType: getTypeAtPosition, @@ -22776,8 +22823,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getShorthandAssignmentValueSymbol(node) : undefined; }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, getExportSymbolOfSymbol: function (symbol) { @@ -22787,8 +22834,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; }, signatureToString: function (signature, enclosingDeclaration, flags, kind) { @@ -22818,41 +22865,41 @@ var ts; getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, - getContextualTypeForArgumentAtIndex: function (node, argIndex) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); }, - getContextualTypeForJsxAttribute: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxAttributeLike); + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); apparentArgumentCount = theArgumentCount; var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; apparentArgumentCount = undefined; return res; }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); }, - isValidPropertyAccessForCompletions: function (node, type, property) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); return !!node && isValidPropertyAccessForCompletions(node, type, property); }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); return declaration ? getSignatureFromDeclaration(declaration) : undefined; }, isImplementationOfOverload: function (node) { @@ -22864,7 +22911,8 @@ var ts; var links = getSymbolLinks(symbol); if (!links.immediateTarget) { var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); links.immediateTarget = getTargetOfAliasDeclaration(node, true); } return links.immediateTarget; @@ -22875,13 +22923,13 @@ var ts; getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); return node ? isOptionalParameter(node) : false; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, @@ -22925,8 +22973,8 @@ var ts; node = ts.getParseTreeNode(node); return node && tryGetThisTypeAt(node); }, - getTypeArgumentConstraint: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file) { @@ -23216,6 +23264,7 @@ var ts; typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); }, buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0; } symbolToString(symbol, enclosingDeclaration, meaning, flags | 4, emitTextWriterWrapper(writer)); }, buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { @@ -23624,7 +23673,7 @@ var ts; if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); @@ -23678,7 +23727,8 @@ var ts; } break; } - return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); } function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { return !!ts.findAncestor(usage, function (current) { @@ -23704,6 +23754,7 @@ var ts; } } } + return false; }); } } @@ -24009,11 +24060,11 @@ var ts; } function checkAndReportErrorForExtendingInterface(errorLocation) { var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64, true)); - if (isError) { + if (expression && resolveEntityName(expression, 64, true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; + return false; } function getEntityNameForExtendingInterface(node) { switch (node.kind) { @@ -24083,7 +24134,8 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 237) ? d : undefined; }); - ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); @@ -24097,7 +24149,7 @@ var ts; } } function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { switch (node.kind) { @@ -24207,6 +24259,7 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { + if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { @@ -24269,6 +24322,7 @@ var ts; return getNodeLinks(expression).resolvedSymbol; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { case 242: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); @@ -24285,17 +24339,18 @@ var ts; return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 241: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); } } function isNonLocalAlias(symbol, excludes) { if (excludes === void 0) { excludes = 67216319 | 67901928 | 1920; } if (!symbol) return false; - return (symbol.flags & (2097152 | excludes)) === 2097152 || (symbol.flags & 2097152 && symbol.flags & 67108864); + return (symbol.flags & (2097152 | excludes)) === 2097152 || !!(symbol.flags & 2097152 && symbol.flags & 67108864); } function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); - return shouldResolve ? resolveAlias(symbol) : symbol; + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); @@ -24303,7 +24358,8 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -24333,7 +24389,8 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); if (node.kind === 248) { checkExpressionCached(node.expression); } @@ -24415,7 +24472,7 @@ var ts; } } else { - ts.Debug.assertNever(name, "Unknown entity name kind."); + throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -24841,7 +24898,7 @@ var ts; } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -24864,13 +24921,18 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { return false; } @@ -24930,7 +24992,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { return { accessibility: 0 }; @@ -24964,6 +25026,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -25045,6 +25110,7 @@ var ts; } } function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0; } return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); function signatureToStringWorker(writer) { var sigOutput; @@ -25062,10 +25128,11 @@ var ts; } } function typeToString(type, enclosingDeclaration, flags, writer) { - if (flags === void 0) { flags = 1048576; } + if (flags === void 0) { flags = 1048576 | 16384; } 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"); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); @@ -25078,6 +25145,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0; } return flags & 9469291; } function createNodeBuilder() { @@ -25142,7 +25210,7 @@ var ts; function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, - flags: flags, + flags: flags || 0, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, @@ -25247,8 +25315,9 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8), undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928, false) : ts.createIdentifier("?"); - return ts.createTypeReferenceNode(name, undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); @@ -25297,7 +25366,7 @@ var ts; if (type.flags & 4194304) { return typeToTypeNodeHelper(type.typeVariable, context); } - ts.Debug.fail("Should be unreachable."); + return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -25529,7 +25598,7 @@ var ts; var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024) { - var decl = ts.firstOrUndefined(propertySymbol.declarations); + var decl = ts.first(propertySymbol.declarations); var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319); if (name && context.tracker.trackSymbol) { context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); @@ -25584,7 +25653,7 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 137 : 134); var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); if (!indexInfo.type && !(context.flags & 2097152)) { context.encounteredError = true; } @@ -25660,7 +25729,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; var dotDotDotToken = isRest ? ts.createToken(24) : undefined; var name = parameterDeclaration @@ -25690,7 +25759,7 @@ var ts; var chain; var isTypeParameter = symbol.flags & 262144; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64)) { - chain = getSymbolChain(symbol, meaning, true); + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, true)); ts.Debug.assert(chain && chain.length > 0); } else { @@ -25715,7 +25784,7 @@ var ts; return accessibleSymbolChain; } if (endOfChain || - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && !(symbol.flags & (2048 | 4096))) { return [symbol]; } @@ -25886,6 +25955,7 @@ var ts; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512)); @@ -26141,22 +26211,22 @@ var ts; } function hasType(target, propertyName) { if (propertyName === 0) { - return getSymbolLinks(target).type; + return !!getSymbolLinks(target).type; } if (propertyName === 2) { - return getSymbolLinks(target).declaredType; + return !!getSymbolLinks(target).declaredType; } if (propertyName === 1) { - return target.resolvedBaseConstructorType; + return !!target.resolvedBaseConstructorType; } if (propertyName === 3) { - return target.resolvedReturnType; + return !!target.resolvedReturnType; } if (propertyName === 4) { var bc = target.resolvedBaseConstraint; - return bc && bc !== circularConstraintType; + return !!bc && bc !== circularConstraintType; } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } function popTypeResolution() { resolutionTargets.pop(); @@ -26164,7 +26234,7 @@ var ts; return resolutionResults.pop(); } function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { case 231: case 232: @@ -26176,8 +26246,7 @@ var ts; default: return true; } - }); - return node && node.parent; + }).parent; } function getTypeOfPrototypeProperty(prototype) { var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); @@ -26275,7 +26344,7 @@ var ts; } return indexerType || anyType; } - var nameType = isLate && checkComputedPropertyName(name); + var nameType = isLate ? checkComputedPropertyName(name) : undefined; var text = isLate ? getLateBoundNameFromType(nameType) : isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : ts.getTextOfPropertyName(name); @@ -26571,7 +26640,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + if (!lastElement || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); @@ -26583,6 +26652,8 @@ var ts; return result; } function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } return pattern.kind === 179 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); @@ -26678,7 +26749,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } else { - ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); } if (!popTypeResolution()) { type = reportCircularityError(symbol); @@ -26874,11 +26945,12 @@ var ts; function check(type) { if (ts.getObjectFlags(type) & (3 | 4)) { var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); + return target === checkBase || ts.some(getBaseTypes(target), check); } else if (type.flags & 262144) { - return ts.forEach(type.types, check); + return ts.some(type.types, check); } + return false; } } function appendTypeParameters(typeParameters, declarations) { @@ -26964,7 +27036,7 @@ var ts; } if (type.flags & 1081344) { var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } @@ -27089,8 +27161,8 @@ var ts; return true; } function isValidBaseType(type) { - return type.flags & (65536 | 134217728 | 1) && !isGenericMappedType(type) || - type.flags & 262144 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return !!(type.flags & (65536 | 134217728 | 1)) && !isGenericMappedType(type) || + !!(type.flags & 262144) && !ts.some(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -27363,7 +27435,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 154 || (returnType && isThislessType(returnType))) && + return (node.kind === 154 || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -27424,7 +27496,7 @@ var ts; } function hasLateBindableName(node) { var name = ts.getNameOfDeclaration(node); - return name && isLateBindableName(name); + return !!name && isLateBindableName(name); } function hasNonBindableDynamicName(node) { return ts.hasDynamicName(node) && !hasLateBindableName(node); @@ -27439,6 +27511,7 @@ var ts; if (type.flags & 96) { return ts.escapeLeadingUnderscores("" + type.value); } + return ts.Debug.fail(); } function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024), "Expected a late-bound symbol."); @@ -27451,8 +27524,7 @@ var ts; symbol.declarations.push(member); } if (symbolFlags & 67216319) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } } @@ -27957,7 +28029,7 @@ var ts; return !!(ts.getObjectFlags(type) & 32 && getMappedTypeModifiers(type) & 4); } function isGenericMappedType(type) { - return ts.getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return !!(ts.getObjectFlags(type) & 32) && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -28515,7 +28587,7 @@ var ts; var hasLiteralTypes = false; var minArgumentCount = 0; var thisParameter = void 0; - var hasThisParameter = void 0; + var hasThisParameter = false; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && @@ -28630,7 +28702,7 @@ var ts; return node.name.kind === 146 && traverse(node.name); default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); } } } @@ -28727,9 +28799,10 @@ var ts; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + var type = getTypeOfSymbol(ts.last(signature.parameters)); if (ts.getObjectFlags(type) & 4 && type.target === globalArrayType) { - return type.typeArguments[0]; + var t = type.typeArguments[0]; + return strictAny && t.flags & 1 ? unknownType : t; } } return anyType; @@ -29023,7 +29096,7 @@ var ts; var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); if (referenceType || assignedType) { - return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; + return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -29074,7 +29147,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return node.flags & 2097152 && node.kind === 161; + return !!(node.flags & 2097152) && node.kind === 161; } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -29121,7 +29194,7 @@ var ts; var indexed = getTypeFromTypeNode(typeArgs[0]); var target = getTypeFromTypeNode(typeArgs[1]); var index = createIndexInfo(target, false); - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); } return anyType; } @@ -29600,16 +29673,19 @@ var ts; return true; } function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); if (includes & 16384) { return neverType; } - if (includes & 1) { - return includes & 33554432 ? wildcardType : anyType; + if (includes & 33554432) { + return wildcardType; + } + if (!strictAny && includes & 1) { + return anyType; + } + if (!strictNullChecks && includes & 12288) { + return includes & 4096 ? undefinedType : nullType; } if (includes & 2 && includes & 32 || includes & 4 && includes & 64 || @@ -29619,6 +29695,9 @@ var ts; if (includes & 67108864 && !(includes & 65536)) { typeSet.push(emptyObjectType); } + if (typeSet.length === 0) { + return anyType; + } if (typeSet.length === 1) { return typeSet[0]; } @@ -29808,12 +29887,12 @@ var ts; var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - t.stringIndexInfo && !t.numberIndexInfo; + !!t.stringIndexInfo && !t.numberIndexInfo; } return false; } function isMappedTypeToNever(type) { - return ts.getObjectFlags(type) & 32 && getTemplateTypeFromMappedType(type) === neverType; + return !!(ts.getObjectFlags(type) & 32) && getTemplateTypeFromMappedType(type) === neverType; } function getSimplifiedType(type) { return type.flags & 1048576 ? getSimplifiedIndexedAccessType(type) : type; @@ -30231,7 +30310,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 8388608 ? type.regularType : type; + return type.flags & 96 && type.flags & 8388608 ? type.regularType : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { var qualifier = typeof value === "number" ? "#" : "@"; @@ -30359,7 +30440,7 @@ var ts; case 71: case 145: var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return (symbol && getDeclaredTypeOfSymbol(symbol)); default: return unknownType; } @@ -30553,21 +30634,21 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; if (ts.findAncestor(node, function (n) { return n.kind === 212 ? "quit" : n === container_3; })) { - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { case 173: - return tp.isThisType; + return !!tp.isThisType; case 71: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; case 164: return true; } - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -30686,9 +30767,9 @@ var ts; case 153: return isContextSensitiveFunctionLikeDeclaration(node); case 183: - return ts.forEach(node.properties, isContextSensitive); + return ts.some(node.properties, isContextSensitive); case 182: - return ts.forEach(node.elements, isContextSensitive); + return ts.some(node.elements, isContextSensitive); case 200: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); @@ -30700,11 +30781,15 @@ var ts; case 190: return isContextSensitive(node.expression); case 262: - return ts.forEach(node.properties, isContextSensitive); - case 261: - return node.initializer && isContextSensitive(node.initializer); - case 264: - return node.expression && isContextSensitive(node.expression); + return ts.some(node.properties, isContextSensitive); + case 261: { + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 264: { + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } } return false; } @@ -30712,7 +30797,7 @@ var ts; if (node.typeParameters) { return false; } - if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } if (node.kind !== 192) { @@ -30721,7 +30806,8 @@ var ts; return true; } } - return node.body.kind === 212 ? false : isContextSensitive(node.body); + var body = node.body; + return body.kind === 212 ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -30929,8 +31015,8 @@ var ts; function isEmptyObjectType(type) { return type.flags & 65536 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 134217728 ? true : - type.flags & 131072 ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 262144 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + type.flags & 131072 ? ts.some(type.types, isEmptyObjectType) : + type.flags & 262144 ? !ts.some(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -31005,7 +31091,7 @@ var ts; if (s & 1024 || t & 1024) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { - if (s & 1) + if (s & 1 && (!strictAny || source === unknownType || t & 65536 && isEmptyObjectType(target))) return true; if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) return true; @@ -31124,6 +31210,7 @@ var ts; return false; } function isRelatedTo(source, target, reportErrors, headMessage) { + if (reportErrors === void 0) { reportErrors = false; } if (source.flags & 96 && source.flags & 8388608) { source = source.regularType; } @@ -31283,7 +31370,8 @@ var ts; var _loop_6 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { - ts.Debug.assert(!!errorNode); + if (!errorNode) + return { value: ts.Debug.fail() }; if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } @@ -31294,8 +31382,9 @@ var ts; var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; - if (ts.isIdentifier(propDeclaration.name)) { - suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); } } if (suggestion !== undefined) { @@ -31870,7 +31959,7 @@ var ts; } } else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { - var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); } else { @@ -31958,7 +32047,7 @@ var ts; return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); } if (isGenericMappedType(source)) { - return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + return (kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); } if (isObjectTypeWithInferableIndex(source)) { var related = -1; @@ -32056,7 +32145,7 @@ var ts; return type.flags & 32768 && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return ts.getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return !!(ts.getObjectFlags(type) & 4) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } function getTypeReferenceId(type, typeParameters, depth) { if (depth === void 0) { depth = 0; } @@ -32264,7 +32353,7 @@ var ts; return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); } function isArrayType(type) { - return ts.getObjectFlags(type) & 4 && type.target === globalArrayType; + return !!(ts.getObjectFlags(type) & 4) && type.target === globalArrayType; } function isArrayLikeType(type) { return ts.getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || @@ -32665,12 +32754,12 @@ var ts; } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); } return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 393216 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 393216) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); @@ -33052,7 +33141,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 16382 | 524288); + return !!constraint && maybeTypeOfKind(constraint, 16382 | 524288); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128); @@ -33072,10 +33161,12 @@ var ts; } function getCovariantInference(inference, context, signature) { var candidates = widenObjectLiteralCandidates(inference.candidates); - var widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; var unwidenedType = context.flags & 1 || inference.priority & 28 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); @@ -33166,7 +33257,8 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 179) { + var parent = element.parent; + if (parent.kind === 179) { var name = element.propertyName || element.name; switch (name.kind) { case 71: @@ -33181,7 +33273,7 @@ var ts; } } else { - return "" + element.parent.elements.indexOf(element); + return "" + parent.elements.indexOf(element); } } function isMatchingReference(source, target) { @@ -33209,7 +33301,7 @@ var ts; } if (source.parent.parent.kind === 231) { var maybeId = source.parent.parent.initializer; - return maybeId && isMatchingReference(maybeId, t.expression); + return !!maybeId && isMatchingReference(maybeId, t.expression); } } return false; @@ -33243,7 +33335,7 @@ var ts; var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -34347,7 +34439,7 @@ var ts; } else if (declaration.kind === 204) { var container = ts.getThisContainer(node, false); - while (container !== undefined) { + while (container.kind !== 273) { if (container.parent === declaration) { if (container.kind === 151 && ts.hasModifier(container, 32)) { getNodeLinks(declaration).flags |= 8388608; @@ -34815,7 +34907,7 @@ var ts; if (funcHasRestParameters && indexOfParameter === (func.parameters.length - 1) && isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + return getTypeOfSymbol(ts.last(contextualSignature.parameters)); } } } @@ -34949,7 +35041,7 @@ var ts; case 6: return false; default: - ts.Debug.assertNever(kind); + return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { @@ -35021,6 +35113,22 @@ var ts; return getContextualType(attribute.parent); } } + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9: + case 8: + case 13: + case 101: + case 86: + case 95: + case 71: + return true; + case 184: + case 190: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); @@ -35034,8 +35142,8 @@ var ts; continue; if (prop.kind !== 269) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -35112,8 +35220,8 @@ var ts; return undefined; } function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -35604,7 +35712,7 @@ var ts; case 71: return ts.isIntrinsicJsxName(tagName.escapedText); default: - ts.Debug.fail(); + return ts.Debug.fail(); } } function checkJsxAttribute(node, checkMode) { @@ -35781,6 +35889,7 @@ var ts; return instantiatedSignatures; } function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (reportErrors === void 0) { reportErrors = false; } if (!node.typeArguments) { return; } @@ -35966,7 +36075,7 @@ var ts; if (!ts.length(instantiatedSignatures)) { return unknownType; } - var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); + var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); @@ -35977,7 +36086,7 @@ var ts; checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(ts.map(instantiatedSignatures, function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, true); })); + return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, true); })); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); @@ -36542,7 +36651,7 @@ var ts; } var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, left, type, prop) - : ts.isInJavaScriptFile(node) && (type.flags & 131072) && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 131072) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); } function getForInVariableSymbol(node) { var initializer = node.initializer; @@ -36673,7 +36782,7 @@ var ts; var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { - index++; + index = index + 1; } else { lastParent = parent; @@ -36709,7 +36818,7 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; var typeArguments; - var callIsIncomplete; + var callIsIncomplete = false; var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { return true; @@ -36718,8 +36827,7 @@ var ts; argCount = args.length; typeArguments = undefined; if (node.template.kind === 201) { - var lastSpan = ts.lastOrUndefined(node.template.templateSpans); - ts.Debug.assert(lastSpan !== undefined); + var lastSpan = ts.last(node.template.templateSpans); callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { @@ -36849,7 +36957,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -36888,7 +36996,7 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { return false; } } @@ -36955,6 +37063,8 @@ var ts; return signature.parameters.length >= 3 ? 3 : 2; case 148: return 3; + default: + return ts.Debug.fail(); } } else { @@ -36998,14 +37108,15 @@ var ts; node.kind === 155 || node.kind === 156) { var element = node; - switch (element.name.kind) { + var name = element.name; + switch (name.kind) { case 71: - return getLiteralType(ts.idText(element.name)); + return getLiteralType(ts.idText(name)); case 8: case 9: - return getLiteralType(element.name.text); + return getLiteralType(name.text); case 146: - var nameType = checkComputedPropertyName(element.name); + var nameType = checkComputedPropertyName(name); if (isTypeAssignableToKind(nameType, 1536)) { return nameType; } @@ -37450,6 +37561,8 @@ var ts; case 155: case 156: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); } } function resolveDecorator(node, candidatesOutArray) { @@ -37470,8 +37583,7 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); invocationErrorRecovery(apparentType, 0); @@ -37519,7 +37631,7 @@ var ts; return ts.length(sigs) ? sigs[0] : unknownSignature; }) || unknownSignature; } - ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); @@ -37539,7 +37651,7 @@ var ts; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; - return symbol && symbol.members !== undefined; + return !!symbol && symbol.members !== undefined; } return false; } @@ -37755,6 +37867,7 @@ var ts; if (node.keywordToken === 91) { return checkImportMetaProperty(node); } + return ts.Debug.assertNever(node.keywordToken); } function checkNewTargetMetaProperty(node) { var container = ts.getNewTargetContainer(node); @@ -37833,9 +37946,9 @@ var ts; } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { - var parameter = ts.lastOrUndefined(signature.parameters); + var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + var contextualParameterType = getTypeOfSymbol(ts.last(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } @@ -38187,7 +38300,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 245; + return !!declaration && declaration.kind === 245; } } } @@ -38305,15 +38418,15 @@ var ts; if (strict && source.flags & (1 | 2048 | 4096 | 8192)) { return false; } - return (kind & 84 && isTypeAssignableTo(source, numberType)) || - (kind & 34 && isTypeAssignableTo(source, stringType)) || - (kind & 136 && isTypeAssignableTo(source, booleanType)) || - (kind & 2048 && isTypeAssignableTo(source, voidType)) || - (kind & 16384 && isTypeAssignableTo(source, neverType)) || - (kind & 8192 && isTypeAssignableTo(source, nullType)) || - (kind & 4096 && isTypeAssignableTo(source, undefinedType)) || - (kind & 512 && isTypeAssignableTo(source, esSymbolType)) || - (kind & 134217728 && isTypeAssignableTo(source, nonPrimitiveType)); + return !!(kind & 84) && isTypeAssignableTo(source, numberType) || + !!(kind & 34) && isTypeAssignableTo(source, stringType) || + !!(kind & 136) && isTypeAssignableTo(source, booleanType) || + !!(kind & 2048) && isTypeAssignableTo(source, voidType) || + !!(kind & 16384) && isTypeAssignableTo(source, neverType) || + !!(kind & 8192) && isTypeAssignableTo(source, nullType) || + !!(kind & 4096) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 512) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 134217728) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { return source.flags & 131072 ? @@ -38321,7 +38434,7 @@ var ts; isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return ts.getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); + return !!(ts.getObjectFlags(type) & 16) && !!type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; @@ -38348,7 +38461,7 @@ var ts; if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 | 1536))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 134217728 | 7372800)) { + if (!(rightType.flags & 1 || isTypeAssignableToKind(rightType, 134217728 | 7372800))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -38685,6 +38798,8 @@ var ts; error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; + default: + return ts.Debug.fail(); } function checkSpecialAssignment(left, right) { var special = ts.getSpecialPropertyAssignmentKind(left.parent); @@ -38769,7 +38884,9 @@ var ts; } } var func = ts.getContainingFunction(node); - var functionFlags = func ? ts.getFunctionFlags(func) : 0; + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); if (!(functionFlags & 1)) { return anyType; } @@ -38865,14 +38982,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 && - constraintDeclaration.operator === 128; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216) { @@ -38881,17 +38990,15 @@ var ts; } if (contextualType.flags & 7372800) { var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 | 64 | 1024) || - constraint.flags & 2 && maybeTypeOfKind(candidateType, 32) || - constraint.flags & 4 && maybeTypeOfKind(candidateType, 64) || - constraint.flags & 8 && maybeTypeOfKind(candidateType, 128) || - constraint.flags & 512 && maybeTypeOfKind(candidateType, 1024) || + return maybeTypeOfKind(constraint, 2) && maybeTypeOfKind(candidateType, 32) || + maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 64) || + maybeTypeOfKind(constraint, 512) && maybeTypeOfKind(candidateType, 1024) || isLiteralOfContextualType(candidateType, constraint); } - return contextualType.flags & (32 | 524288) && maybeTypeOfKind(candidateType, 32) || + return !!(contextualType.flags & (32 | 524288) && maybeTypeOfKind(candidateType, 32) || contextualType.flags & 64 && maybeTypeOfKind(candidateType, 64) || contextualType.flags & 128 && maybeTypeOfKind(candidateType, 128) || - contextualType.flags & 1024 && maybeTypeOfKind(candidateType, 1024); + contextualType.flags & 1024 && maybeTypeOfKind(candidateType, 1024)); } return false; } @@ -39284,20 +39391,21 @@ var ts; else { var isStatic = ts.hasModifier(member, 32); var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { switch (member.kind) { case 155: - addName(names, member.name, memberName, 1); + addName(names, name, memberName, 1); break; case 156: - addName(names, member.name, memberName, 2); + addName(names, name, memberName, 2); break; case 151: - addName(names, member.name, memberName, 3); + addName(names, name, memberName, 3); break; case 153: - addName(names, member.name, memberName, 4); + addName(names, name, memberName, 4); break; } } @@ -39350,13 +39458,14 @@ var ts; var member = _a[_i]; if (member.kind === 150) { var memberName = void 0; - switch (member.name.kind) { + var name = member.name; + switch (name.kind) { case 9: case 8: - memberName = member.name.text; + memberName = name.text; break; case 71: - memberName = ts.idText(member.name); + memberName = ts.idText(name); break; default: continue; @@ -39936,7 +40045,7 @@ var ts; case 247: return 1; default: - ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); } } } @@ -40020,7 +40129,8 @@ var ts; var thenFunction = getTypeOfPropertyOfType(type, "then"); if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); + if (!diagnosticMessage) + return ts.Debug.fail(); error(errorNode, diagnosticMessage); } return undefined; @@ -40095,11 +40205,11 @@ var ts; break; case 148: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; case 151: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 153: case 155: @@ -40108,6 +40218,8 @@ var ts; var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; + default: + return ts.Debug.fail(); } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } @@ -40392,13 +40504,6 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 231 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 147) { - return; - } - } var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(0, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } @@ -40471,6 +40576,7 @@ var ts; return; var unusedImports = ts.createMap(); var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); nodeWithLocals.locals.forEach(function (local) { if (local.flags & 262144 ? !(local.flags & 3 && !(local.isReferenced & 3)) : local.isReferenced || local.exportSymbol) { return; @@ -40488,6 +40594,11 @@ var ts; addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + if (!isIdentifierThatStartsWithUnderScore(declaration.name) || !ts.isForInOrOfStatement(declaration.parent.parent)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + } else { var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); if (parameter) { @@ -40505,47 +40616,74 @@ var ts; unusedImports.forEach(function (_a) { var importClause = _a[0], unuseds = _a[1]; var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 245 ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(0, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { var unused = unuseds_1[_i]; errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } } - else if (unuseds.length === 1) { - addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); - } - else { - addDiagnostic(0, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); - } }); unusedDestructures.forEach(function (_a) { var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 : 0; - if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 231 && bindingPattern.parent.parent.kind === 232) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } } - else if (bindingElements.length === 1) { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(0, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 213 ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(0, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + } } }); } + function bindingNameText(name) { + switch (name.kind) { + case 71: + return ts.idText(name); + case 180: + case 179: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } function isImportedDeclaration(node) { return node.kind === 244 || node.kind === 247 || node.kind === 245; } function importClauseFromImported(decl) { return decl.kind === 244 ? decl : decl.kind === 245 ? decl.parent : decl.parent.parent; } - function forEachImportedDeclaration(importClause, cb) { - var defaultName = importClause.name, namedBindings = importClause.namedBindings; - return (defaultName && cb(importClause)) || - namedBindings && (namedBindings.kind === 245 ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); - } function checkBlock(node) { if (node.kind === 212) { checkGrammarStatementInAmbientContext(node); @@ -40605,6 +40743,7 @@ var ts; } return true; } + return false; }); } function checkIfNewTargetIsCapturedInEnclosingScope(node) { @@ -40619,6 +40758,7 @@ var ts; } return true; } + return false; }); } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -40959,7 +41099,7 @@ var ts; checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - if (rightType === neverType || !isTypeAssignableToKind(rightType, 134217728 | 7372800)) { + if (rightType === neverType || !(rightType.flags & 1 || isTypeAssignableToKind(rightType, 134217728 | 7372800))) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -41077,11 +41217,11 @@ var ts; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); if (isTypeAny(methodType)) { return undefined; } - var signatures = methodType && getSignaturesOfType(methodType, 0); + var signatures = methodType ? getSignaturesOfType(methodType, 0) : undefined; if (!ts.some(signatures)) { if (errorNode) { reportTypeNotIterableError(errorNode, type, allowAsyncIterables); @@ -41175,7 +41315,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 ? getPromisedTypeOfPromise(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 | 1); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 | 1); } function checkReturnStatement(node) { if (checkGrammarStatementInAmbientContext(node)) { @@ -41283,6 +41423,7 @@ var ts; grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } + return false; }); } checkSourceElement(node.statement); @@ -41338,8 +41479,8 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (ts.getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 && ts.isClassLike(classDeclaration)) { for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; if (!ts.hasModifier(member, 32) && hasNonBindableDynamicName(member)) { @@ -41440,8 +41581,8 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { var name = symbolToString(symbol); - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -41450,8 +41591,8 @@ var ts; function areTypeParametersIdentical(declarations, targetParameters) { var maxTypeArgumentCount = ts.length(targetParameters); var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); var numTypeParameters = sourceParameters.length; if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { @@ -41660,7 +41801,7 @@ var ts; if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { continue; } - if (isPrototypeProperty(base) && isPrototypeProperty(derived) || base.flags & 98308 && derived.flags & 98308) { + if (isPrototypeProperty(base) || base.flags & 98308 && derived.flags & 98308) { continue; } var errorMessage = void 0; @@ -41893,7 +42034,11 @@ var ts; case 190: return evaluate(expr.expression); case 71: - return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); case 185: case 184: var ex = expr; @@ -41984,8 +42129,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if ((declaration.kind === 234 || (declaration.kind === 233 && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304)) { @@ -42035,7 +42180,7 @@ var ts; if (symbol.flags & 512 && symbol.declarations.length > 1 && !inAmbientContext - && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -42149,7 +42294,7 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (ts.nodeIsMissing(moduleName)) { + if (!moduleName || ts.nodeIsMissing(moduleName)) { return false; } if (!ts.isStringLiteral(moduleName)) { @@ -42374,8 +42519,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -42397,11 +42542,11 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var tags = _a[_i].tags; - ts.forEach(tags, checkSourceElement); - } + if (ts.isInJavaScriptFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); } var kind = node.kind; if (cancellationToken) { @@ -42570,7 +42715,7 @@ var ts; if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } - var paramTag = parent.parent; + var paramTag = node.parent.parent; if (!ts.isJSDocParameterTag(paramTag)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); return; @@ -42587,8 +42732,8 @@ var ts; function getTypeFromJSDocVariadicType(node) { var type = getTypeFromTypeNode(node.type); var parent = node.parent; - var paramTag = parent.parent; - if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { var host_1 = ts.getHostSignatureFromJSDoc(paramTag); if (host_1) { var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); @@ -42610,8 +42755,8 @@ var ts; } } function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; + for (var _i = 0, _a = deferredNodes; _i < _a.length; _i++) { + var node = _a[_i]; switch (node.kind) { case 191: case 192: @@ -42638,9 +42783,9 @@ var ts; function unusedIsError(kind) { switch (kind) { case 0: - return compilerOptions.noUnusedLocals; + return !!compilerOptions.noUnusedLocals; case 1: - return compilerOptions.noUnusedParameters; + return !!compilerOptions.noUnusedParameters; default: return ts.Debug.assertNever(kind); } @@ -42798,21 +42943,21 @@ var ts; case 236: case 237: return true; + default: + return false; } } - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 145) { + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 145) { node = node.parent; } - return node.parent && node.parent.kind === 161; + return node.parent.kind === 161; } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 184) { + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 184) { node = node.parent; } - return node.parent && node.parent.kind === 206; + return node.parent.kind === 206; } function forEachEnclosingClass(node, callback) { var result; @@ -42844,10 +42989,10 @@ var ts; nodeOnRightSide = nodeOnRightSide.parent; } if (nodeOnRightSide.parent.kind === 242) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } if (nodeOnRightSide.parent.kind === 248) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; } @@ -42977,23 +43122,25 @@ var ts; if (node.kind === 273) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } + var parent = node.parent; + var grandParent = parent.parent; if (node.flags & 8388608) { return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { - return getSymbolOfNode(node.parent); + return getSymbolOfNode(parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); + return getSymbolOfNode(parent.parent); } if (node.kind === 71) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 181 && - node.parent.parent.kind === 179 && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); + else if (parent.kind === 181 && + grandParent.kind === 179 && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; @@ -43035,10 +43182,10 @@ var ts; return resolveExternalModuleName(node, node); } case 8: - var objectType = ts.isElementAccessExpression(node.parent) - ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined - : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) - ? getTypeFromTypeNode(node.parent.parent.objectType) + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79: @@ -43186,9 +43333,9 @@ var ts; } return target; } - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var isPropertyName_1 = node.parent.kind === 184 && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; @@ -43216,11 +43363,10 @@ var ts; } } function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); if (symbol) { @@ -43244,8 +43390,8 @@ var ts; } } } - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); if (isNonLocalAlias(symbol, 67216319)) { @@ -43279,9 +43425,9 @@ var ts; } return false; } - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { @@ -43291,8 +43437,8 @@ var ts; } return undefined; } - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); if (node) { var symbol = getSymbolOfNode(node); if (symbol) { @@ -43311,7 +43457,7 @@ var ts; return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 249: var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); case 248: return node.expression && node.expression.kind === 71 @@ -43320,8 +43466,8 @@ var ts; } return false; } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); if (node === undefined || node.parent.kind !== 273 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } @@ -43333,11 +43479,11 @@ var ts; if (target === unknownSymbol) { return true; } - return target.flags & 67216319 && + return !!(target.flags & 67216319) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { if (ts.isAliasSymbolDeclaration(node)) { @@ -43351,7 +43497,7 @@ var ts; } } if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); } return false; } @@ -43367,10 +43513,10 @@ var ts; return false; } function isRequiredInitializedParameter(parameter) { - return strictNullChecks && + return !!strictNullChecks && !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && - parameter.initializer && + !!parameter.initializer && !ts.hasModifier(parameter, 92); } function isOptionalUninitializedParameterProperty(parameter) { @@ -43380,7 +43526,7 @@ var ts; ts.hasModifier(parameter, 92); } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + return getNodeLinks(node).flags || 0; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -43408,10 +43554,10 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 65536 && getSignaturesOfType(type, 0).length > 0; + return !!(type.flags & 65536) && getSignaturesOfType(type, 0).length > 0; } - function getTypeReferenceSerializationKind(typeName, location) { - typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + function getTypeReferenceSerializationKind(typeNameIn, location) { + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); if (!typeName) return ts.TypeReferenceSerializationKind.Unknown; if (location) { @@ -43432,7 +43578,7 @@ var ts; } } if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -43469,8 +43615,8 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { - declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { return ts.createToken(119); } @@ -43487,16 +43633,16 @@ var ts; } return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024, tracker); } - function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { - signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { return ts.createToken(119); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, tracker); } - function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { - expr = ts.getParseTreeNode(expr, ts.isExpression); + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { return ts.createToken(119); } @@ -43520,9 +43666,9 @@ var ts; } return resolveName(location, reference.escapedText, 67216319 | 1048576 | 2097152, undefined, undefined, true); } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); if (reference) { var symbol = getReferencedValueSymbol(reference); if (symbol) { @@ -43575,7 +43721,7 @@ var ts; }, getNodeCheckFlags: function (node) { node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; + return node ? getNodeCheckFlags(node) : 0; }, isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, @@ -43588,8 +43734,8 @@ var ts; createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, collectLinkedAliases: collectLinkedAliases, @@ -43602,8 +43748,8 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - isLateBound: function (node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024); }, @@ -43804,7 +43950,7 @@ var ts; case 16384: return "__asyncValues"; case 32768: return "__exportStar"; case 65536: return "__makeTemplateObject"; - default: ts.Debug.fail("Unrecognized helper"); + default: return ts.Debug.fail("Unrecognized helper"); } } function resolveHelpersModule(node, errorNode) { @@ -44018,7 +44164,7 @@ var ts; else if (flags & 64) { return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); } - return; + return false; } else if ((node.kind === 243 || node.kind === 242) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); @@ -44032,6 +44178,7 @@ var ts; if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); } + return false; } function reportObviousModifierErrors(node) { return !node.modifiers @@ -44098,6 +44245,7 @@ var ts; if (list && list.hasTrailingComma) { return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); } + return false; } function checkGrammarTypeParameterList(typeParameters, file) { if (typeParameters && typeParameters.length === 0) { @@ -44105,6 +44253,7 @@ var ts; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); } + return false; } function checkGrammarParameterList(parameters) { var seenOptionalParameter = false; @@ -44195,6 +44344,7 @@ var ts; if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } + return false; } function checkGrammarIndexSignature(node) { return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); @@ -44206,6 +44356,7 @@ var ts; var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); } + return false; } function checkGrammarTypeArguments(node, typeArguments) { return checkGrammarForDisallowedTrailingComma(typeArguments) || @@ -44220,6 +44371,7 @@ var ts; } } } + return false; } function checkGrammarArguments(args) { return checkGrammarForOmittedArgument(args); @@ -44233,7 +44385,7 @@ var ts; var listType = ts.tokenToString(node.token); return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } - return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + return ts.some(types, checkGrammarExpressionWithTypeArguments); } function checkGrammarExpressionWithTypeArguments(node) { return checkGrammarTypeArguments(node, node.typeArguments); @@ -44295,6 +44447,7 @@ var ts; if (computedPropertyName.expression.kind === 199 && computedPropertyName.expression.operatorToken.kind === 26) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } + return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { @@ -44310,9 +44463,7 @@ var ts; } } function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } + return !!questionToken && grammarErrorOnNode(questionToken, message); } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; @@ -44361,7 +44512,7 @@ var ts; currentKind = 4; break; default: - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -44487,6 +44638,7 @@ var ts; } } } + return false; } function doesAccessorHaveCorrectParameterCount(accessor) { return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 155 ? 0 : 1); @@ -44690,6 +44842,7 @@ var ts; } } } + return false; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 71) { @@ -44706,6 +44859,7 @@ var ts; } } } + return false; } function checkGrammarVariableDeclarationList(declarationList) { var declarations = declarationList.declarations; @@ -44715,6 +44869,7 @@ var ts; if (!declarationList.declarations.length) { return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } + return false; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { @@ -44766,6 +44921,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); @@ -44773,6 +44929,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorOnNode(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -44780,6 +44937,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; } + return false; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); @@ -44846,6 +45004,7 @@ var ts; } } } + return false; } function checkGrammarSourceFile(node) { return !!(node.flags & 4194304) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); @@ -44868,6 +45027,7 @@ var ts; else { } } + return false; } function checkGrammarNumericLiteral(node) { if (node.numericLiteralFlags & 32) { @@ -44887,6 +45047,7 @@ var ts; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } + return false; } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -44895,6 +45056,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), 0, message, arg0, arg1, arg2)); return true; } + return false; } function getAmbientModules() { if (!ambientModulesCache) { @@ -44921,6 +45083,7 @@ var ts; if (ts.isSpreadElement(nodeArguments[0])) { return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); } + return false; } } ts.createTypeChecker = createTypeChecker; @@ -44990,7 +45153,7 @@ var ts; ts.createNodeArray = createNodeArray; function getSynthesizedClone(node) { if (node === undefined) { - return undefined; + return node; } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; @@ -46502,6 +46665,7 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0; } var node = createSynthesizedNode(232); node.flags |= flags & 3; node.declarations = createNodeArray(declarations); @@ -46623,6 +46787,7 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0; } var node = createSynthesizedNode(238); node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); @@ -47118,6 +47283,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -47736,7 +47903,7 @@ var ts; ts.createSpreadHelper = createSpreadHelper; function createForOfBindingStatement(node, boundValue) { if (ts.isVariableDeclarationList(node)) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); + var firstDeclaration = ts.first(node.declarations); var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, undefined, boundValue); return ts.setTextRange(ts.createVariableStatement(undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), node); } @@ -47790,6 +47957,7 @@ var ts; } } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } var callee = skipOuterExpressions(expression, 7); var thisArg; var target; @@ -47876,7 +48044,7 @@ var ts; switch (property.kind) { case 155: case 156: - return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); case 269: return createExpressionForPropertyAssignment(property, receiver); case 270: @@ -47953,6 +48121,7 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { var name = ts.getMutableClone(nodeName); @@ -47977,7 +48146,7 @@ var ts; function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); ts.setTextRange(qualifiedName, name); - var emitFlags; + var emitFlags = 0; if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -47992,7 +48161,8 @@ var ts; } ts.convertToFunctionBody = convertToFunctionBody; function convertFunctionDeclarationToExpression(node) { - ts.Debug.assert(!!node.body); + if (!node.body) + return ts.Debug.fail(); var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); @@ -48037,7 +48207,7 @@ var ts; ts.addStandardPrologue = addStandardPrologue; function addCustomPrologue(target, source, statementOffset, visitor) { var numStatements = source.length; - while (statementOffset < numStatements) { + while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); @@ -48496,8 +48666,9 @@ var ts; return bindingElement.initializer; } if (ts.isPropertyAssignment(bindingElement)) { - return ts.isAssignmentExpression(bindingElement.initializer, true) - ? bindingElement.initializer.right + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, true) + ? initializer.right : undefined; } if (ts.isShorthandPropertyAssignment(bindingElement)) { @@ -49432,7 +49603,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function liftToBlock(nodes) { @@ -49560,7 +49731,7 @@ var ts; return ts.some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { - return e.propertyName && e.propertyName.escapedText === "default"; + return e.propertyName !== undefined && e.propertyName.escapedText === "default"; } function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; @@ -49593,7 +49764,7 @@ var ts; } ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { - return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -49783,7 +49954,7 @@ var ts; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: true, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -49848,13 +50019,14 @@ var ts; return false; } function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } var pendingExpressions; var pendingDeclarations = []; var declarations = []; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: hoistTempVariables, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -49880,7 +50052,7 @@ var ts; } else { context.hoistVariableDeclaration(temp); - var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + var pendingDeclaration = ts.last(pendingDeclarations); pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); pendingDeclaration.value = temp; @@ -50484,7 +50656,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ @@ -51074,7 +51246,8 @@ var ts; return serializedUnion || ts.createVoidZero(); } function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -51100,8 +51273,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } function serializeEntityNameAsExpression(node, useFallback) { @@ -51370,7 +51544,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); @@ -51400,7 +51574,7 @@ var ts; } } function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } function hasNamespaceQualifiedExportName(node) { return isExportOfNamespace(node) @@ -51515,7 +51689,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -51973,8 +52147,9 @@ var ts; : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } function visitForStatementInAsyncBody(node) { - return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) - ? visitVariableDeclarationListWithCollidingNames(node.initializer, false) + var initializer = node.initializer; + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, false) : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } function visitAwaitExpression(node) { @@ -52015,10 +52190,10 @@ var ts; } } function isVariableDeclarationListWithCollidingName(node) { - return node + return !!node && ts.isVariableDeclarationList(node) && !(node.flags & 3) - && ts.forEach(node.declarations, collidesWithParameterName); + && node.declarations.some(collidesWithParameterName); } function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { hoistVariableDeclarationList(node); @@ -52085,7 +52260,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); if (languageVersion >= 2) { @@ -52596,7 +52771,7 @@ var ts; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { @@ -52622,7 +52797,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -53416,7 +53591,7 @@ var ts; hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return hierarchyFacts & 4096 + return (hierarchyFacts & 4096) !== 0 && node.kind === 224 && !node.expression; } @@ -53556,7 +53731,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0, 0); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -53625,7 +53800,8 @@ var ts; (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; - if (!node.label) { + var label = node.label; + if (!label) { if (node.kind === 223) { convertedLoopState.nonLocalJumps |= 2; labelMarker = "break"; @@ -53637,12 +53813,12 @@ var ts; } else { if (node.kind === 223) { - labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, true, ts.idText(node.label), labelMarker); + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, true, ts.idText(label), labelMarker); } else { - labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, false, ts.idText(node.label), labelMarker); + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, false, ts.idText(label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -53725,7 +53901,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); ts.setEmitFlags(block, 1536); return block; @@ -53751,7 +53927,7 @@ var ts; convertedLoopState = savedConvertedLoopState; } function transformConstructorParameters(constructor, hasSynthesizedSuper) { - return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { @@ -53772,7 +53948,7 @@ var ts; } ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); } - var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); if (superCaptureStatus === 1 || superCaptureStatus === 2) { statementOffset++; @@ -53788,7 +53964,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, false); } @@ -54190,7 +54366,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, false); if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { multiLine = true; @@ -54293,11 +54469,10 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 - && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); if (firstDeclaration) { - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); } } return declarationList; @@ -54392,35 +54567,34 @@ var ts; } function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { var statements = []; - if (ts.isVariableDeclarationList(node.initializer)) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { if (node.initializer.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } - var firstOriginalDeclaration = ts.firstOrUndefined(node.initializer.declarations); + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0, boundValue); var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer); ts.setOriginalNode(declarationList, node.initializer); - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { statements.push(ts.setTextRange(ts.createVariableStatement(undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, boundValue) - ]), ts.moveRangePos(node.initializer, -1)), node.initializer)), ts.moveRangeEnd(node.initializer, -1))); + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); } } else { - var assignment = ts.createAssignment(node.initializer, boundValue); + var assignment = ts.createAssignment(initializer, boundValue); if (ts.isDestructuringAssignment(assignment)) { ts.aggregateTransformFlags(assignment); statements.push(ts.createStatement(visitBinaryExpression(assignment, false))); } else { - assignment.end = node.initializer.end; - statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); } } if (convertedLoopBodyStatements) { @@ -54595,7 +54769,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, true); } if (ts.isBlock(loopBody)) { @@ -54789,7 +54963,7 @@ var ts; case 156: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; case 153: @@ -54897,7 +55071,7 @@ var ts; } function visitArrayLiteralExpression(node) { if (node.transformFlags & 64) { - return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); + return transformAndSpreadElements(node.elements, true, !!node.multiLine, !!node.elements.hasTrailingComma); } return ts.visitEachChild(node, visitor, context); } @@ -54912,11 +55086,11 @@ var ts; } function visitTypeScriptClassWrapper(node) { var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); - var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); - var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); var variable = varStatement.declarationList.declarations[0]; var initializer = ts.skipOuterExpressions(variable.initializer); var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); @@ -55179,14 +55353,13 @@ var ts; return node; } function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { + switch (node.parent.kind) { case 181: case 234: case 237: case 231: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); } return false; } @@ -55354,7 +55527,7 @@ var ts; } function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token >= 72 && token <= 107) { + if (token !== undefined && token >= 72 && token <= 107) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -55416,6 +55589,7 @@ var ts; case 4: return "yield"; case 5: return "yield*"; case 7: return "endfinally"; + default: return undefined; } } function transformGenerators(context) { @@ -55634,7 +55808,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); inGeneratorFunctionBody = savedInGeneratorFunctionBody; inStatementContainingYield = savedInStatementContainingYield; @@ -55672,13 +55846,14 @@ var ts; } } function visitBinaryExpression(node) { - switch (ts.getExpressionAssociativity(node)) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { case 0: return visitLeftAssociativeBinaryExpression(node); case 1: return visitRightAssociativeBinaryExpression(node); default: - ts.Debug.fail("Unknown associativity."); + return ts.Debug.assertNever(assoc); } } function isCompoundAssignment(kind) { @@ -56332,7 +56507,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 16777216) !== 0; + return !!node && (node.transformFlags & 16777216) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -56419,7 +56594,8 @@ var ts; } function endBlock() { var block = peekBlock(); - ts.Debug.assert(block !== undefined, "beginBlock was never called."); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); var index = blockActions.length; blockActions[index] = 1; blockOffsets[index] = operations ? operations.length : 0; @@ -56662,7 +56838,7 @@ var ts; return 0; } function createLabel(label) { - if (label > 0) { + if (label !== undefined && label > 0) { if (labelExpressions === undefined) { labelExpressions = []; } @@ -57100,7 +57276,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); @@ -57215,7 +57391,7 @@ var ts; } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); @@ -58019,7 +58195,7 @@ var ts; ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); ts.addRange(statements, hoistedStatements); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -58477,7 +58653,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -58500,9 +58676,6 @@ var ts; && shouldHoistVariableDeclarationList(node); } function visitForInitializer(node) { - if (!node) { - return node; - } if (shouldHoistForInitializer(node)) { var expressions = void 0; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { @@ -58976,7 +59149,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 231 || node.kind === 181) { @@ -59101,7 +59274,7 @@ var ts; ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; break; default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); } return { diagnosticMessage: diagnosticMessage, @@ -59166,7 +59339,7 @@ var ts; ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; default: - ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); } } function getTypeParameterConstraintVisibilityError() { @@ -59203,7 +59376,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } return { diagnosticMessage: diagnosticMessage, @@ -59362,7 +59535,7 @@ var ts; var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) - return; + return undefined; hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -59583,7 +59756,7 @@ var ts; return false; } if (ts.isBindingPattern(elem.name)) { - return ts.forEach(elem.name.elements, getBindingNameVisible); + return ts.some(elem.name.elements, getBindingNameVisible); } else { return resolver.isDeclarationVisible(elem); @@ -59625,7 +59798,7 @@ var ts; } function rewriteModuleSpecifier(parent, input) { if (!input) - return; + return undefined; resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 238 && parent.kind !== 178); if (input.kind === 9 && isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -60654,7 +60827,7 @@ var ts; } if (node) { var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var range = emitNode && emitNode.sourceMapRange; var _a = range || node, pos = _a.pos, end = _a.end; var source = range && range.source; @@ -60694,7 +60867,7 @@ var ts; return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128) === 0 && tokenPos >= 0) { @@ -60728,7 +60901,7 @@ var ts; } function getText() { if (disabled) { - return; + return undefined; } encodeLastRecordedSourceMapSpan(); return JSON.stringify({ @@ -60743,7 +60916,7 @@ var ts; } function getSourceMappingURL() { if (disabled) { - return; + return undefined; } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.base64encode(ts.sys, getText()); @@ -60795,7 +60968,7 @@ var ts; var currentLineMap; var detachedCommentsInfo; var hasWrittenComment = false; - var disabled = printerOptions.removeComments; + var disabled = !!printerOptions.removeComments; return { reset: reset, setWriter: setWriter, @@ -60813,7 +60986,7 @@ var ts; if (node) { hasWrittenComment = false; var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; if ((pos < 0 && end < 0) || (pos === end)) { emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); @@ -61077,10 +61250,10 @@ var ts; detachedCommentsInfo = undefined; } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { - var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -61120,6 +61293,7 @@ var ts; var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { @@ -61149,7 +61323,7 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { @@ -61211,7 +61385,7 @@ var ts; emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, - sourceMaps: sourceMapDataList + sourceMaps: sourceMapDataList, }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -61304,7 +61478,7 @@ var ts; if (sourceMapFilePath) { ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), false, sourceFiles); } - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); if (bundleInfoPath) { bundleInfo.totalLength = writer.getTextPos(); ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), false); @@ -61540,8 +61714,7 @@ var ts; return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode); - onEmitNode(hint, node, getNextPipelinePhase(0, hint)); + ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0, hint)); } function pipelineEmitWithComments(hint, node) { ts.Debug.assertDefined(emitNodeWithComments); @@ -61553,9 +61726,8 @@ var ts; pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assertDefined(onEmitSourceMapOfNode); ts.Debug.assert(hint !== 0 && hint !== 2); - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); + ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { if (hint === 0) @@ -63185,7 +63357,7 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) @@ -63429,7 +63601,7 @@ var ts; if (isUndefined && format & 8192) { return; } - var isEmpty = isUndefined || start >= children.length || count === 0; + var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 16384) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -63470,7 +63642,7 @@ var ts; increaseIndent(); } var previousSibling = void 0; - var shouldDecreaseIndentAfterEmit = void 0; + var shouldDecreaseIndentAfterEmit = false; for (var i = 0; i < count; i++) { var child = children[start + i]; if (previousSibling) { @@ -64056,7 +64228,7 @@ var ts; case 3: return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16), !!(name.autoGenerateFlags & 8)); } - ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } function getNodeForGeneratedName(name) { var autoGenerateId = name.autoGenerateId; @@ -64723,8 +64895,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -64752,7 +64923,7 @@ var ts; function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; - var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; + var oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -64769,7 +64940,7 @@ var ts; var modulesWithElidedImports = ts.createMap(); var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); - host = host || createCompilerHost(options); + var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); @@ -65251,7 +65422,7 @@ var ts; return nodes; } function isSourceFileFromExternalLibrary(file) { - return sourceFilesFoundSearchingNodeModules.get(file.path); + return !!sourceFilesFoundSearchingNodeModules.get(file.path); } function isSourceFileDefaultLibrary(file) { if (file.hasNoDefaultLib) { @@ -65265,7 +65436,7 @@ var ts; return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } } function getDiagnosticsProducingTypeChecker() { @@ -65382,11 +65553,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } function shouldReportDiagnostic(diagnostic) { @@ -66274,9 +66453,9 @@ var ts; if (ts.isObjectLiteralExpression(pathProp.initializer)) { for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { var keyProps = _b[_a]; - if (ts.isArrayLiteralExpression(keyProps.initializer) && - keyProps.initializer.elements.length > valueIndex) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); needCompilerDiagnostic = false; } } @@ -66378,6 +66557,7 @@ var ts; return false; } programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + return false; } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); @@ -66395,13 +66575,16 @@ var ts; if (out) { return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts"); } + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { var filePathWithoutExtension = ts.removeFileExtension(filePath); - return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts")) || - !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx")); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts")) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx")); } return false; } @@ -66529,7 +66712,7 @@ var ts; for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var version_1 = sourceFile.version; - var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -66576,7 +66759,8 @@ var ts; return false; } var info = state.fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); + if (!info) + return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { @@ -66701,7 +66885,7 @@ var ts; var ts; (function (ts) { function hasSameKeys(map1, map2) { - return map1 === map2 || map1 && map2 && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); } function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); @@ -66723,7 +66907,7 @@ var ts; ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); } var referencedMap = state.referencedMap; - var oldReferencedMap = useOldState && oldState.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -66889,7 +67073,7 @@ var ts; assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); if (!targetSourceFile) { var sourceMaps = []; - var emitSkipped = void 0; + var emitSkipped = false; var diagnostics = void 0; var emittedFiles = []; var affectedEmitResult = void 0; @@ -67000,7 +67184,7 @@ var ts; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); - var rootPath = rootDir && resolutionHost.toPath(rootDir); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); var typeRootsWatches = ts.createMap(); return { startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, @@ -67052,7 +67236,7 @@ var ts; return false; } var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); - return value && !!value.length; + return !!value && !!value.length; } function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { @@ -67061,7 +67245,7 @@ var ts; } var collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = undefined; - return function (path) { return (collected && collected.has(path)) || + return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { @@ -67394,7 +67578,7 @@ var ts; removeResolutionsOfFile(filePath); invalidateResolutions(function (resolution, getResolutionWithResolvedFileName) { var result = getResolutionWithResolvedFileName(resolution); - return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; }); } function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { @@ -67441,7 +67625,7 @@ var ts; return rootPath; } var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { @@ -67663,9 +67847,9 @@ var ts; system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { - reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); - var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; return host; @@ -67709,7 +67893,7 @@ var ts; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; - var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } @@ -67759,7 +67943,7 @@ var ts; readFile: readFile, trace: trace, directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), realpath: host.realpath && (function (s) { return host.realpath(s); }), getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), onReleaseOldSourceFile: onReleaseOldSourceFile, @@ -68385,6 +68569,13 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, + { + name: "strictAny", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_any_type + }, { name: "strictNullChecks", type: "boolean", @@ -68869,7 +69060,7 @@ var ts; case "string": return ts.map(values, function (v) { return v || ""; }); default: - return ts.filter(ts.map(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }), function (v) { return !!v; }); + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); } } ts.parseListTypeOption = parseListTypeOption; @@ -69248,6 +69439,7 @@ var ts; var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } + return false; } function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); @@ -69669,13 +69861,10 @@ var ts; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return undefined; + return false; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; + return typeof result === "boolean" && result; } function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; @@ -69704,7 +69893,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -70347,7 +70536,7 @@ var ts; ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { var target = climbPastPropertyAccess(node); - return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -70410,6 +70599,8 @@ var ts; return true; case 177: return node.parent.parent.kind === 175; + default: + return false; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -70573,7 +70764,7 @@ var ts; } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { + if (n === undefined || ts.nodeIsMissing(n)) { return false; } switch (n.kind) { @@ -70620,7 +70811,7 @@ var ts; } return hasChildOfKind(n, 20, sourceFile); case 238: - return n.body && isCompletedNode(n.body, sourceFile); + return !!n.body && isCompletedNode(n.body, sourceFile); case 216: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); @@ -70684,11 +70875,11 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last_2 = ts.lastOrUndefined(children); - if (last_2.kind === expectedLastToken) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { return true; } - else if (last_2.kind === 25 && children.length !== 1) { + else if (lastChild.kind === 25 && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -70730,6 +70921,7 @@ var ts; } ts.getTouchingToken = getTouchingToken; function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { + if (includeEndPosition === void 0) { includeEndPosition = false; } return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeEndPosition, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; @@ -70895,10 +71087,11 @@ var ts; var tokenKind = token.kind; var remainingMatchingTokens = 0; while (true) { - token = findPrecedingToken(token.getFullStart(), sourceFile); - if (!token) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { return undefined; } + token = preceding; if (token.kind === matchingTokenKind) { if (remainingMatchingTokens === 0) { return token; @@ -70911,15 +71104,18 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(token, sourceFile) { + function isPossiblyTypeArgumentPosition(tokenIn, sourceFile) { + var token = tokenIn; var remainingLessThanTokens = 0; + var nTypeArguments = 0; while (token) { switch (token.kind) { case 27: token = findPrecedingToken(token.getFullStart(), sourceFile); - var tokenIsIdentifier = token && ts.isIdentifier(token); - if (!remainingLessThanTokens || !tokenIsIdentifier) { - return tokenIsIdentifier; + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return { called: token, nTypeArguments: nTypeArguments }; } remainingLessThanTokens--; break; @@ -70935,19 +71131,21 @@ var ts; case 18: token = findPrecedingMatchingToken(token, 17, sourceFile); if (!token) - return false; + return undefined; break; case 20: token = findPrecedingMatchingToken(token, 19, sourceFile); if (!token) - return false; + return undefined; break; case 22: token = findPrecedingMatchingToken(token, 21, sourceFile); if (!token) - return false; + return undefined; break; case 26: + nTypeArguments++; + break; case 36: case 71: case 9: @@ -70966,11 +71164,11 @@ var ts; if (ts.isTypeNode(token)) { break; } - return false; + return undefined; } token = findPrecedingToken(token.getFullStart(), sourceFile); } - return false; + return undefined; } ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; function isInComment(sourceFile, position, tokenAtPosition, predicate) { @@ -71180,14 +71378,14 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier) { + function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { return ts.createImportDeclaration(undefined, undefined, defaultImport || namedImports ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) - : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier, preferences.quotePreference === "single") : moduleSpecifier); } ts.makeImport = makeImport; function symbolNameNoDefault(symbol) { @@ -71406,18 +71604,21 @@ var ts; } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0; } return mapToDisplayParts(function (writer) { - typechecker.writeType(type, enclosingDeclaration, flags | 1024, writer); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 | 16384, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0; } return mapToDisplayParts(function (writer) { typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0; } flags |= 16384 | 1024 | 32 | 8192; return mapToDisplayParts(function (writer) { typechecker.writeSignature(signature, enclosingDeclaration, flags, undefined, writer); @@ -71425,7 +71626,7 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return location.parent && + return !!location.parent && (location.parent.kind === 247 || location.parent.kind === 251) && location.parent.propertyName === location; } @@ -71448,7 +71649,7 @@ var ts; scriptKinds[_i - 2] = arguments[_i]; } var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); } ts.scriptKindIs = scriptKindIs; function getScriptKind(fileName, host) { @@ -71757,6 +71958,8 @@ var ts; case 9: case 17: return ts.TokenClass.Identifier; + default: + return undefined; } } function canFollow(keyword1, keyword2) { @@ -71976,6 +72179,7 @@ var ts; case 22: return "jsx attribute"; case 23: return "jsx text"; case 24: return "jsx attribute string literal value"; + default: return undefined; } } function convertClassificationsToSpans(classifications) { @@ -72198,18 +72402,19 @@ var ts; } if (ts.isPunctuation(tokenKind)) { if (token) { + var parent = token.parent; if (tokenKind === 58) { - if (token.parent.kind === 231 || - token.parent.kind === 151 || - token.parent.kind === 148 || - token.parent.kind === 261) { + if (parent.kind === 231 || + parent.kind === 151 || + parent.kind === 148 || + parent.kind === 261) { return 5; } } - if (token.parent.kind === 199 || - token.parent.kind === 197 || - token.parent.kind === 198 || - token.parent.kind === 200) { + if (parent.kind === 199 || + parent.kind === 197 || + parent.kind === 198 || + parent.kind === 200) { return 5; } } @@ -72496,8 +72701,8 @@ var ts; var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); }); var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); }); if (fragmentDirectory !== undefined) { - var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); - return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); }); + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); } return nonRelativeModuleNames; } @@ -72634,7 +72839,7 @@ var ts; return ts.directoryProbablyExists(path, host); } catch (_a) { } - return undefined; + return false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; @@ -72691,7 +72896,7 @@ var ts; && (contextToken.kind === 72 || contextToken.kind === 77 || contextToken.kind === 71)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(program, log, sourceFile, position, preferences, undefined); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, undefined); if (!completionData) { return undefined; } @@ -72754,7 +72959,7 @@ var ts; }] }; } var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { + if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } @@ -72770,6 +72975,9 @@ var ts; } return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } function isMemberCompletionKind(kind) { switch (kind) { case 0: @@ -72944,7 +73152,7 @@ var ts; case 186: case 187: if (!ts.isRequireCall(node.parent, false) && !ts.isImportCall(node.parent)) { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); } case 243: @@ -72987,7 +73195,8 @@ var ts; : ts.emptyArray; } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { - var completionData = getCompletionData(program, log, sourceFile, position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); if (!completionData) { return { type: "none" }; } @@ -72997,7 +73206,7 @@ var ts; var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; return ts.firstDefined(symbols, function (symbol) { var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - var info = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, origin, completionKind); + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; @@ -73102,11 +73311,13 @@ var ts; CompletionKind[CompletionKind["None"] = 5] = "None"; })(CompletionKind || (CompletionKind = {})); function getRecommendedCompletion(currentToken, position, sourceFile, checker) { - var ty = getContextualType(currentToken, position, sourceFile, checker); - var symbol = ty && ty.symbol; - return symbol && (symbol.flags & 384 || symbol.flags & 32 && !ts.isAbstractConstructorSymbol(symbol)) - ? getFirstSymbolInChain(symbol, currentToken, checker) - : undefined; + var contextualType = getContextualType(currentToken, position, sourceFile, checker); + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + return symbol && (symbol.flags & (8 | 384 | 32) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, currentToken, checker) + : undefined; + }); } function getContextualType(currentToken, position, sourceFile, checker) { var parent = currentToken.parent; @@ -73131,7 +73342,7 @@ var ts; case 17: return ts.isJsxExpression(parent) && parent.parent.kind !== 254 ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: - var argInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(currentToken, position, sourceFile); + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(currentToken, position, sourceFile); return argInfo ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (currentToken.kind === 26 ? 1 : 0)) : isEqualityOperatorKind(currentToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) @@ -73168,7 +73379,7 @@ var ts; function isModuleSymbol(symbol) { return symbol.declarations.some(function (d) { return d.kind === 273; }); } - function getCompletionData(program, log, sourceFile, position, preferences, detailsEntryId) { + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, false); @@ -73246,6 +73457,7 @@ var ts; node = parent.left; break; case 178: + case 209: node = parent; break; default: @@ -73343,6 +73555,8 @@ var ts; case 294: case 296: return true; + default: + return false; } } function getTypeScriptMemberSymbols() { @@ -73375,13 +73589,18 @@ var ts; } } } + if (ts.isMetaProperty(node) && (node.keywordToken === 94 || node.keywordToken === 91)) { + var completion = (node.keywordToken === 94) ? "target" : "meta"; + symbols.push(typeChecker.createSymbol(4, ts.escapeLeadingUnderscores(completion))); + return; + } if (!isTypeLocation) { addTypeProperties(typeChecker.getTypeAtLocation(node)); } } function addTypeProperties(type) { isNewIdentifierLocation = hasIndexSignature(type); - if (ts.isSourceFileJavaScript(sourceFile)) { + if (isUncheckedFile) { symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, true)); } else { @@ -73477,7 +73696,7 @@ var ts; return false; if (ts.programContainsEs6Modules(program)) return true; - if (ts.isSourceFileJavaScript(sourceFile)) + if (isUncheckedFile) return false; return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -73549,6 +73768,7 @@ var ts; var exportedSymbols = typeChecker.getExportsOfModule(symbol); return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); } + return false; } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { var tokenTextLowerCase = tokenText.toLowerCase(); @@ -73614,7 +73834,7 @@ var ts; return true; } if (contextToken.parent.kind === 257 || contextToken.parent.kind === 255) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 254; + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 254; } } return false; @@ -73753,7 +73973,7 @@ var ts; if (!ts.isClassLike(decl)) return 1; var classElement = contextToken.parent; - var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0; if (contextToken.kind === 71 && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { case "private": @@ -73793,13 +74013,14 @@ var ts; } function tryGetConstructorLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 19: case 26: - return ts.isConstructorDeclaration(contextToken.parent) && contextToken.parent; + return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; default: if (isConstructorParameterCompletion(contextToken)) { - return contextToken.parent.parent; + return parent.parent; } } } @@ -73816,6 +74037,7 @@ var ts; return true; } prev_1 = node; + return false; }); return container && container; } @@ -73858,7 +74080,8 @@ var ts; return undefined; } function isSolelyIdentifierDefinitionLocation(contextToken) { - var containingNodeKind = contextToken.parent.kind; + var parent = contextToken.parent; + var containingNodeKind = parent.kind; switch (contextToken.kind) { case 26: return containingNodeKind === 231 || @@ -73869,9 +74092,9 @@ var ts; containingNodeKind === 235 || containingNodeKind === 180 || containingNodeKind === 236 || - (ts.isClassLike(contextToken.parent) && - contextToken.parent.typeParameters && - contextToken.parent.typeParameters.end >= contextToken.pos); + (ts.isClassLike(parent) && + !!parent.typeParameters && + parent.typeParameters.end >= contextToken.pos); case 23: return containingNodeKind === 180; case 56: @@ -73890,15 +74113,14 @@ var ts; containingNodeKind === 236 || ts.isFunctionLikeKind(containingNodeKind); case 115: - return containingNodeKind === 151 && !ts.isClassLike(contextToken.parent.parent); + return containingNodeKind === 151 && !ts.isClassLike(parent.parent); case 24: return containingNodeKind === 148 || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 180); + (!!parent.parent && parent.parent.kind === 180); case 114: case 112: case 113: - return containingNodeKind === 148 && !ts.isConstructorDeclaration(contextToken.parent.parent); + return containingNodeKind === 148 && !ts.isConstructorDeclaration(parent.parent); case 118: return containingNodeKind === 247 || containingNodeKind === 251 || @@ -73981,7 +74203,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 181 && m.propertyName) { + if (ts.isBindingElement(m) && m.propertyName) { if (m.propertyName.kind === 71) { existingName = m.propertyName.escapedText; } @@ -74268,7 +74490,7 @@ var ts; if (!sourceFilesSet.has(fileName)) { ts.Debug.assert(program.redirectTargetsSet.has(fileName)); var redirectTarget_1 = program.getSourceFile(fileName); - var redirect = ts.find(sourceFilesToSearch, function (f) { return f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; ts.Debug.assert(sourceFilesSet.has(fileName)); } @@ -74336,7 +74558,7 @@ var ts; return [node]; } else if (ts.isTryStatement(node)) { - return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), aggregateOwnedThrowStatements(node.finallyBlock)); + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); } return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); } @@ -74369,7 +74591,7 @@ var ts; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; + return !!actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { @@ -74415,9 +74637,8 @@ var ts; } case 154: case 153: - case 233: { + case 233: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - } case 234: case 204: var nodes = container.members; @@ -74614,6 +74835,10 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); @@ -74634,8 +74859,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -74666,23 +74890,40 @@ var ts; var bucket = getBucketForCompilationSettings(key, true); var entry = bucket.get(path); var scriptTarget = scriptKind === 6 ? 100 : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } if (!entry) { var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, false, scriptKind); + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } else { if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } if (acquiring) { entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -74700,6 +74941,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -74707,11 +74955,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); var ts; (function (ts) { @@ -74959,7 +75208,7 @@ var ts; } function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); - return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { if (!ts.isExportDeclaration(statement)) return; var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; @@ -75055,10 +75304,11 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; + var grandParent = parent.parent; if (symbol.exportSymbol) { if (parent.kind === 184) { - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) - ? getSpecialPropertyExport(parent.parent, false) + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, false) : undefined; } else { @@ -75082,14 +75332,14 @@ var ts; else if (ts.isExportAssignment(parent)) { return getExportAssignmentExport(parent); } - else if (ts.isExportAssignment(parent.parent)) { - return getExportAssignmentExport(parent.parent); + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); } else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, true); } - else if (ts.isBinaryExpression(parent.parent)) { - return getSpecialPropertyExport(parent.parent, true); + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0); @@ -75155,6 +75405,9 @@ var ts; else if (ts.isBinaryExpression(decl)) { return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } function getExportNode(parent, node) { @@ -75430,19 +75683,20 @@ var ts; } var moduleReferences = ts.emptyArray; var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; if (moduleSourceFile) { var exportEquals = symbol.exports.get("export="); moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) return moduleReferences; symbol = ts.skipAlias(exportEquals, checker); - node = undefined; + referencedNode = undefined; } - return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; function isModuleSymbol(symbol) { - return symbol.flags & 1536 && ts.find(symbol.declarations, ts.isSourceFile); + return symbol.flags & 1536 ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; } function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); @@ -75510,7 +75764,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 }, state); } else { - var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); var scope = getSymbolScope(symbol); if (scope) { getReferencesInContainer(scope, scope.getSourceFile(), search, state, !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); @@ -75583,13 +75837,13 @@ var ts; State.prototype.getImportSearches = function (exportSymbol, exportInfo) { if (!this.importTracker) this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); - return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); }; 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 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; State.prototype.referenceAdder = function (searchSymbol) { @@ -75675,8 +75929,9 @@ var ts; } } function getPropertySymbolOfDestructuringAssignment(location, checker) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - checker.getPropertySymbolOfDestructuringAssignment(location); + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; } function getObjectBindingElementWithoutPropertyName(symbol) { var bindingElement = ts.getDeclarationOfKind(symbol, 181); @@ -75714,8 +75969,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { return undefined; @@ -75890,7 +76145,8 @@ var ts; if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 ? 1 : 0; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - ts.Debug.assert(!!exportInfo); + if (!exportInfo) + return ts.Debug.fail(); searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); } if (search.comingFrom !== 1 && exportDeclaration.moduleSpecifier && !propertyName) { @@ -76006,8 +76262,7 @@ var ts; }); } function findSuperConstructorAccesses(cls, addNode) { - var symbol = cls.symbol; - var ctr = symbol.members.get("__constructor"); + var ctr = cls.symbol.members.get("__constructor"); if (!ctr) { return; } @@ -76274,8 +76529,8 @@ var ts; var lastIterationMeaning = void 0; do { lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -76328,6 +76583,69 @@ var ts; })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); var ts; +(function (ts) { + function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { + var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; + var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); + if (newPath !== undefined) { + var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); + changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); + } + } + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); + if (oldFile) { + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + } + } + function isRef(toUpdate) { + return "fileName" in toUpdate; + } + function getImportsToUpdate(program, oldFilePath, host) { + var result = []; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var ref = _c[_b]; + if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { + result.push({ sourceFile: sourceFile, toUpdate: ref }); + } + } + for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { + var importStringLiteral = _e[_d]; + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { + result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); + } + } + } + return result; + } + function getPathUpdater(oldFilePath, newFilePath, host) { + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + return function (oldPath) { + if (!ts.pathIsRelative(oldPath)) + return; + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + }; + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } +})(ts || (ts = {})); +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -76340,6 +76658,7 @@ var ts; if (node === sourceFile) { return undefined; } + var parent = node.parent; if (ts.isJumpStatementTarget(node)) { var label = ts.getTargetLabel(node.parent, node.text); return label ? [createDefinitionInfoFromName(label, "label", node.text, undefined)] : undefined; @@ -76353,7 +76672,7 @@ var ts; if (calledDeclaration) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) || - symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, false); }) + symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, false); }) ? [sigInfo] : [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node)); } @@ -76361,9 +76680,9 @@ var ts; var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; } - if (ts.isPropertyName(node) && ts.isBindingElement(node.parent) && ts.isObjectBindingPattern(node.parent.parent) && - (node === (node.parent.propertyName || node.parent.name))) { - var type = typeChecker.getTypeAtLocation(node.parent.parent); + if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var type = typeChecker.getTypeAtLocation(parent.parent); if (type) { var propSymbols = ts.getPropertySymbolsFromType(type, node); if (propSymbols) { @@ -76516,13 +76835,13 @@ var ts; kind: "script", name: name, containerName: undefined, - containerKind: undefined + containerKind: undefined, }; } function getAncestorCallLikeExpression(node) { var target = climbPastManyPropertyAccesses(node); var callLike = target.parent; - return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; } function climbPastManyPropertyAccesses(node) { return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; @@ -76826,7 +77145,7 @@ var ts; return rightHandSide.parameters; case 204: { var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); - return ctr && ctr.parameters; + return ctr ? ctr.parameters : ts.emptyArray; } } return ts.emptyArray; @@ -77134,7 +77453,7 @@ var ts; case 0: return ts.Debug.fail(); default: - ts.Debug.assertNever(result); + throw ts.Debug.assertNever(result); } } JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; @@ -77174,8 +77493,8 @@ var ts; if (!match) { return; } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -77236,12 +77555,12 @@ var ts; if (name.kind === 146 && !tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { return undefined; } - declaration = ts.getContainerNode(declaration); + container = ts.getContainerNode(container); } return containers; } @@ -77685,7 +78004,7 @@ var ts; } } function hasSomeImportantChild(item) { - return ts.forEach(item.children, function (child) { + return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); return childKind !== 231 && childKind !== 181; }); @@ -77848,12 +78167,12 @@ var ts; OrganizeImports.organizeImports = organizeImports; function getModuleBlock(moduleDecl) { var body = moduleDecl.body; - return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -77887,7 +78206,7 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { @@ -78037,70 +78356,6 @@ var ts; })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); var ts; -(function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); - return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { - var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; - var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); - if (newPath !== undefined) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } - }); - } - ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); - } - } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var checker = program.getTypeChecker(); - var result = []; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (!program.getSourceFileFromReference(sourceFile, ref) && ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - if (checker.getSymbolAtLocation(importStringLiteral)) - continue; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } - } - return result; - } - function getPathUpdater(oldFilePath, newFilePath, host) { - var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; - } - function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); - } -})(ts || (ts = {})); -var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { @@ -78312,7 +78567,7 @@ var ts; } ts.createPatternMatcher = createPatternMatcher; function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) { - var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments), stringToWordSpans); + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); if (!candidateMatch) { return undefined; } @@ -78871,7 +79126,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; } else { var ambientModuleNames = void 0; @@ -78889,7 +79144,7 @@ var ts; } } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -78999,7 +79254,12 @@ var ts; ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); + })(ArgumentListKind || (ArgumentListKind = {})); + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + })(InvocationKind || (InvocationKind = {})); function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { var typeChecker = program.getTypeChecker(); var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); @@ -79010,63 +79270,83 @@ var ts; if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); - var call = argumentInfo.invocation; - var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker); cancellationToken.throwIfCancellationRequested(); - if (!candidates.length) { + if (!candidateInfo) { if (ts.isSourceFileJavaScript(sourceFile)) { return createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken); } return undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { - if (argumentInfo.invocation.kind !== 186) { - return undefined; + function getCandidateInfo(argumentInfo, checker) { + var invocation = argumentInfo.invocation; + if (invocation.kind === 0) { + var candidates = []; + var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; } - var callExpression = argumentInfo.invocation; - var expression = callExpression.expression; + else { + var type = checker.getTypeAtLocation(invocation.called); + var signatures = ts.isNewExpression(invocation.called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + var candidates = signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= argumentInfo.argumentCount; }); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + } + function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + var expression = getExpressionFromInvocation(argumentInfo.invocation); var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + var _loop_16 = function (sourceFile) { var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_16 = function (declaration) { + var _loop_17 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); if (type) { var callSignatures_1 = type.getCallSignatures(); if (callSignatures_1 && callSignatures_1.length) { - return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, typeChecker); }) }; + return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; } } } }; - for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { - var declaration = declarations_12[_b]; - var state_5 = _loop_16(declaration); - if (typeof state_5 === "object") - return state_5.value; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var state_6 = _loop_17(declaration); + if (typeof state_6 === "object") + return state_6; } } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var state_5 = _loop_16(sourceFile); + if (typeof state_5 === "object") + return state_5.value; } } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.kind === 0 || info.invocation.kind === 1 ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (ts.isCallOrNewExpression(node.parent)) { - var invocation = node.parent; + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; var list = void 0; var argumentIndex = void 0; if (node.kind === 27 || node.kind === 19) { - list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); + list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); ts.Debug.assert(list !== undefined); argumentIndex = 0; } @@ -79076,52 +79356,58 @@ var ts; return undefined; argumentIndex = getArgumentIndex(list, node); } - var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 : 1; + var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 : 1; var argumentCount = getArgumentCount(list); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + return { kind: kind, invocation: { kind: 0, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 && node.parent.kind === 188) { + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { if (ts.isInsideTemplateLiteral(node, position)) { - return getArgumentListInfoForTemplate(node.parent, 0, sourceFile); + return getArgumentListInfoForTemplate(parent, 0, sourceFile); } } - else if (node.kind === 14 && node.parent.parent.kind === 188) { - var templateExpression = node.parent; + else if (ts.isTemplateHead(node) && parent.parent.kind === 188) { + var templateExpression = parent; var tagExpression = templateExpression.parent; ts.Debug.assert(templateExpression.kind === 201); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 210 && node.parent.parent.parent.kind === 188) { - var templateSpan = node.parent; - var templateExpression = templateSpan.parent; - var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 201); + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; if (node.kind === 16 && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } - var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position); return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent && ts.isJsxOpeningLikeElement(node.parent)) { - var attributeSpanStart = node.parent.attributes.getFullStart(); - var attributeSpanEnd = ts.skipTrivia(sourceFile.text, node.parent.attributes.getEnd(), false); + else if (ts.isJsxOpeningLikeElement(parent)) { + var attributeSpanStart = parent.attributes.pos; + var attributeSpanEnd = ts.skipTrivia(sourceFile.text, parent.attributes.end, false); return { kind: 3, - invocation: node.parent, + invocation: { kind: 0, node: parent }, argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart), argumentIndex: 0, argumentCount: 1 }; } + else { + var typeArgInfo = ts.isPossiblyTypeArgumentPosition(node, sourceFile); + if (typeArgInfo) { + var called = typeArgInfo.called, nTypeArguments = typeArgInfo.nTypeArguments; + var invocation = { kind: 1, called: called }; + var argumentsSpan = ts.createTextSpanFromBounds(called.getStart(sourceFile), node.end); + return { kind: 0, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; + } + } return undefined; } - SignatureHelp.getImmediatelyContainingArgumentInfo = getImmediatelyContainingArgumentInfo; function getArgumentIndex(argumentsList, node) { var argumentIndex = 0; for (var _i = 0, _a = argumentsList.getChildren(); _i < _a.length; _i++) { @@ -79138,7 +79424,7 @@ var ts; function getArgumentCount(argumentsList) { var listChildren = argumentsList.getChildren(); var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 26; }); - if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 26) { + if (listChildren.length > 0 && ts.last(listChildren).kind === 26) { argumentCount++; } return argumentCount; @@ -79160,7 +79446,7 @@ var ts; } return { kind: 2, - invocation: tagExpression, + invocation: { kind: 0, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, argumentCount: argumentCount @@ -79176,7 +79462,7 @@ var ts; var applicableSpanStart = template.getStart(); var applicableSpanEnd = template.getEnd(); if (template.kind === 201) { - var lastSpan = ts.lastOrUndefined(template.templateSpans); + var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); } @@ -79184,36 +79470,38 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 273; n = n.parent) { - if (ts.isFunctionBlock(n)) { - return undefined; - } - if (n.pos < n.parent.pos || n.end > n.parent.end) { - ts.Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); - } + var _loop_18 = function (n) { + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); if (argumentInfo) { - return argumentInfo; + return { value: argumentInfo }; } + }; + for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { + var state_7 = _loop_18(n); + if (typeof state_7 === "object") + return state_7.value; } return undefined; } - SignatureHelp.getContainingArgumentInfo = getContainingArgumentInfo; function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { var children = parent.getChildren(sourceFile); var indexOfOpenerToken = children.indexOf(openerToken); ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 ? ts.getInvokedExpression(invocation.node) : invocation.called; + } var signatureHelpNodeBuilderFlags = 8192 | 3112960; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0; - var callTarget = ts.getInvokedExpression(invocation); - var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); + var enclosingDeclaration = invocation.kind === 0 ? invocation.node : invocation.called; + var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, undefined, undefined); var printer = ts.createPrinter({ removeComments: true }); - var items = ts.map(candidates, function (candidateSignature) { + var items = candidates.map(function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; var suffixDisplayParts = []; @@ -79228,9 +79516,9 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296, params, sourceFile, writer); }); ts.addRange(suffixDisplayParts, parameterParts); } @@ -79238,8 +79526,8 @@ var ts; isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); - printer.writeList(26896, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896, args, sourceFile, writer); } }); ts.addRange(prefixDisplayParts, typeParameterParts); @@ -79252,10 +79540,10 @@ var ts; writer.writeSpace(" "); var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); if (predicate) { - typeChecker.writeTypePredicate(predicate, invocation, undefined, writer); + typeChecker.writeTypePredicate(predicate, enclosingDeclaration, undefined, writer); } else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, undefined, writer); + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, undefined, writer); } }); ts.addRange(suffixDisplayParts, returnTypeParts); @@ -79277,8 +79565,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); - printer.writeNode(4, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4, param, sourceFile, writer); }); return { name: parameter.name, @@ -79289,8 +79577,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); - printer.writeNode(4, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, @@ -79319,8 +79607,7 @@ var ts; case 233: case 191: if (isJsFile) { - var symbol = node.symbol; - if (symbol.members && (symbol.members.size > 0)) { + if (node.symbol.members && (node.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)); } } @@ -79359,6 +79646,7 @@ var ts; } } } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; @@ -79388,7 +79676,7 @@ var ts; switch (node.kind) { case 243: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings.kind === 245 && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 245 && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; case 242: @@ -79521,7 +79809,7 @@ var ts; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - var hasAddedSymbolInfo; + var hasAddedSymbolInfo = false; var isThisExpression = location.kind === 99 && ts.isExpression(location); var type; var printer; @@ -79690,7 +79978,8 @@ var ts; } else { var decl = ts.getDeclarationOfKind(symbol, 147); - ts.Debug.assert(decl !== undefined); + if (decl === undefined) + return ts.Debug.fail(); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { @@ -79927,6 +80216,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0; } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); @@ -80029,7 +80319,8 @@ var ts; ts.addRange(diagnostics, program.getOptionsDiagnostics()); } program.emit(undefined, undefined, undefined, undefined, transpileOptions.transformers); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } ts.transpileModule = transpileModule; @@ -80045,7 +80336,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_19 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -80061,7 +80352,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_19(opt); } return options; } @@ -80195,7 +80486,7 @@ var ts; lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4; + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4; } else { scanner.scan(); @@ -80845,7 +81136,7 @@ var ts; } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - context.contextNode.decorators && + !!context.contextNode.decorators && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -81089,7 +81380,7 @@ var ts; return ts.rangeContainsRange(parent.members, node); case 238: var body = parent.body; - return body && body.kind === 239 && ts.rangeContainsRange(body.statements, node); + return !!body && body.kind === 239 && ts.rangeContainsRange(body.statements, node); case 273: case 212: case 239: @@ -82171,8 +82462,9 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0; + switch (parent.kind) { case 215: case 234: case 204: @@ -82194,7 +82486,6 @@ var ts; case 186: case 187: case 213: - case 231: case 248: case 224: case 200: @@ -82217,22 +82508,14 @@ var ts; case 246: case 251: case 247: - case 269: case 151: return true; - } - return false; - } - function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { - var childKind = child ? child.kind : 0; - switch (parent.kind) { case 231: case 269: - case 183: if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183) { return rangeIsOnOneLine(sourceFile, child); } - break; + return true; case 217: case 218: case 220: @@ -82256,6 +82539,11 @@ var ts; return childKind !== 257; case 258: return childKind !== 260; + case 169: + case 168: + if (childKind === 165) { + return false; + } } return indentByDefault; } @@ -82279,7 +82567,7 @@ var ts; } function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(settings, parent, child, sourceFile, false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; @@ -82378,7 +82666,7 @@ var ts; : end; } function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 || (candidate.kind === 25 && node.parent.kind === 183)); + return !!candidate && !!node.parent && (candidate.kind === 26 || (candidate.kind === 25 && node.parent.kind === 183)); } function spaces(count) { var s = ""; @@ -82754,7 +83042,7 @@ var ts; var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); } return changes; }; @@ -82776,13 +83064,13 @@ var ts; 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) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_20 = 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 - 1; i++) { - _loop_18(i); + _loop_20(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -82791,8 +83079,11 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter) { - var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; @@ -83497,20 +83788,20 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); } } }); return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -83520,7 +83811,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, undefined, moduleSpecifier, preferences)); break; case 186: if (ts.isRequireCall(importNode, false)) { @@ -83530,14 +83821,14 @@ var ts; } } } - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { 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); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -83571,17 +83862,17 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { switch (statement.kind) { case 213: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); return false; case 215: { var expression = statement.expression; switch (expression.kind) { case 186: { if (ts.isRequireCall(expression, true)) { - changes.replaceNode(sourceFile, statement, ts.makeImport(undefined, undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(undefined, undefined, expression.arguments[0], preferences)); } return false; } @@ -83595,7 +83886,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -83607,11 +83898,11 @@ var ts; } else if (ts.isRequireCall(initializer, true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); } } return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); @@ -83620,20 +83911,20 @@ var ts; changes.replaceNodeWithNodes(sourceFile, statement, newNodes); } } - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { switch (name.kind) { case 179: case 180: { var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), + makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), makeConst(undefined, name, ts.createIdentifier(tmp)), ]; } case 71: - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } function convertAssignment(sourceFile, checker, assignment, changes, exports) { @@ -83747,7 +84038,7 @@ var ts; return makeConst(modifiers, ts.createIdentifier(name), exported); } } - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { switch (name.kind) { case 179: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { @@ -83756,23 +84047,23 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [ts.makeImport(undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(undefined, importSpecifiers, moduleSpecifier, preferences)]; } } case 180: { var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier, preferences), makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { var nameSymbol = checker.getSymbolAtLocation(name); var namedBindingsNames = ts.createMap(); var needDefaultImport = false; @@ -83803,7 +84094,7 @@ var ts; if (!namedBindings) { needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; } function makeUniqueName(name, identifiers) { while (identifiers.original.has(name) || identifiers.additional.has(name)) { @@ -83839,10 +84130,10 @@ var ts; 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) { + function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier) - : ts.makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier, preferences) + : ts.makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -83960,7 +84251,9 @@ var ts; ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, ], - getCodeActions: getImportCodeActions, + getCodeActions: function (context) { return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(context) + : getActionsForNonUMDImport(context); }, fixIds: [], getAllCodeActions: ts.notImplemented, }); @@ -83977,7 +84270,6 @@ var ts; program: program, checker: checker, compilerOptions: program.getCompilerOptions(), - cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(context.host)), symbolName: symbolName, symbolToken: symbolToken, @@ -84021,22 +84313,39 @@ var ts; return result; } function getCodeActionsForImport_separateExistingAndNew(exportInfos, context, useExisting, addNew) { - var existingImports = ts.flatMap(exportInfos, function (info) { - return getImportDeclarations(info, context.checker, context.sourceFile, context.cachedImportDeclarations); - }); - if (context.symbolToken && ts.isIdentifier(context.symbolToken)) { - for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) { - var declaration = existingImports_1[_i].declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); - if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); - } + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, context.checker, context.sourceFile); }); + ts.append(useExisting, tryUseExistingNamespaceImport(existingImports, context, context.symbolToken, context.checker)); + var addToExisting = tryAddToExistingImport(existingImports, context); + if (addToExisting) { + useExisting.push(addToExisting); + } + else { + getCodeActionsForAddImport(exportInfos, context, existingImports, addNew); + } + } + function tryUseExistingNamespaceImport(existingImports, context, symbolToken, checker) { + return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = namespace && checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { + return getCodeActionForUseExistingNamespaceImport(namespace.text, context, symbolToken); } } - } - getCodeActionsForAddImport(exportInfos, context, existingImports, useExisting, addNew); + }); + } + function tryAddToExistingImport(existingImports, context) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind === 243 && declaration.importClause) { + var changes = tryUpdateExistingImport(context, declaration.importClause, importKind); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [context.symbolName, moduleSpecifierWithoutQuotes], changes); + } + } + }); } function getNamespaceImportName(declaration) { if (declaration.kind === 243) { @@ -84047,20 +84356,14 @@ var ts; return declaration.name; } } - function getImportDeclarations(_a, checker, _b, cachedImportDeclarations) { + function getExistingImportDeclarations(_a, checker, _b) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; var imports = _b.imports; - if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } - var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (moduleSpecifier) { - var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 243 || i.kind === 242) - && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; - }); - } - return cached; + return ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 243 || i.kind === 242) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); } function getCodeActionForNewImport(context, _a) { var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; @@ -84111,21 +84414,7 @@ var ts; }); return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { - var fromExistingImport = ts.firstDefined(existingImports, function (_a) { - var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 243 && declaration.importClause) { - var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined, importKind); - if (changes) { - var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); - return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes); - } - } - }); - if (fromExistingImport) { - useExisting.push(fromExistingImport); - return; - } + function getCodeActionsForAddImport(exportInfos, ctx, existingImports, addNew) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] @@ -84182,11 +84471,6 @@ var ts; }); return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes); } - function getImportCodeActions(context) { - return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ? getActionsForUMDImport(context) - : getActionsForNonUMDImport(context); - } function getActionsForUMDImport(context) { var token = ts.getTokenAtPosition(context.sourceFile, context.span.start, false); var checker = context.program.getTypeChecker(); @@ -84240,7 +84524,14 @@ var ts; if (!symbolName) return undefined; ts.Debug.assert(symbolName !== "default"); - var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + var addToExistingDeclaration = []; + var addNewDeclaration = []; + getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).forEach(function (exportInfos) { + getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration); + }); + return addToExistingDeclaration.concat(addNewDeclaration); + } + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); @@ -84261,7 +84552,7 @@ var ts; addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0); } function getEscapedNameForExportDefault(symbol) { - return ts.firstDefined(symbol.declarations, function (declaration) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { if (ts.isExportAssignment(declaration)) { if (ts.isIdentifier(declaration.expression)) { return declaration.expression.escapedText; @@ -84269,19 +84560,12 @@ var ts; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.escapedText === "default"); - if (declaration.propertyName) { - return declaration.propertyName.escapedText; - } + return declaration.propertyName && declaration.propertyName.escapedText; } }); } }); - var addToExistingDeclaration = []; - var addNewDeclaration = []; - originalSymbolToExportInfos.forEach(function (exportInfos) { - getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration); - }); - return addToExistingDeclaration.concat(addNewDeclaration); + return originalSymbolToExportInfos; } function checkSymbolHasMeaning(_a, meaning) { var declarations = _a.declarations; @@ -84303,7 +84587,7 @@ var ts; for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { var sourceFile = allSourceFiles_1[_b]; if (ts.isExternalOrCommonJsModule(sourceFile)) { - cb(sourceFile.symbol, sourceFile); + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } @@ -84817,7 +85101,9 @@ var ts; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - doChange(changes, context.sourceFile, getInfo(diag.file, diag.start, diag.code)); + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); }); }, }); function getInfo(sourceFile, pos, diagCode) { @@ -84846,20 +85132,26 @@ var ts; ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { var errorCode = context.errorCode, sourceFile = context.sourceFile; - var importDecl = tryGetFullImport(sourceFile, context.span.start); + var startToken = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var importDecl = tryGetFullImport(startToken); if (importDecl) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } - var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start, undefined); }); + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, startToken, undefined); }); if (delDestructure.length) { return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(t, sourceFile, startToken, undefined); }); + if (delVar.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, undefined); }); @@ -84874,9 +85166,10 @@ var ts; }, fixIds: [fixIdPrefix, fixIdDelete], getAllCodeActions: function (context) { - var deleted = new NodeSet(); + var deleted = new ts.NodeSet(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var sourceFile = context.sourceFile; + var startToken = ts.getTokenAtPosition(sourceFile, diag.start, false); var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); switch (context.fixId) { case fixIdPrefix: @@ -84887,14 +85180,12 @@ var ts; case fixIdDelete: if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); })) break; - var importDecl = tryGetFullImport(diag.file, diag.start); + var importDecl = tryGetFullImport(startToken); if (importDecl) { changes.deleteNode(sourceFile, importDecl); } - else { - if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) { - tryDeleteDeclaration(changes, sourceFile, token, deleted); - } + else if (!tryDeleteFullDestructure(changes, sourceFile, startToken, deleted) && !tryDeleteFullVariableStatement(changes, sourceFile, startToken, deleted)) { + tryDeleteDeclaration(changes, sourceFile, token, deleted); } break; default: @@ -84903,15 +85194,13 @@ var ts; }); }, }); - function tryGetFullImport(sourceFile, pos) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, false); + function tryGetFullImport(startToken) { return startToken.kind === 91 ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; } - function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, false); + function tryDeleteFullDestructure(changes, sourceFile, startToken, deletedAncestors) { if (startToken.kind !== 17 || !ts.isObjectBindingPattern(startToken.parent)) return false; - var decl = startToken.parent.parent; + var decl = ts.cast(startToken.parent, ts.isObjectBindingPattern).parent; switch (decl.kind) { case 231: tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors); @@ -84931,6 +85220,16 @@ var ts; } return true; } + function tryDeleteFullVariableStatement(changes, sourceFile, startToken, deletedAncestors) { + var declarationList = ts.tryCast(startToken.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === startToken) { + if (deletedAncestors) + deletedAncestors.add(declarationList); + changes.deleteNode(sourceFile, declarationList.parent.kind === 213 ? declarationList.parent : declarationList); + return true; + } + return false; + } function getToken(sourceFile, pos) { var token = ts.findPrecedingToken(pos, sourceFile, undefined, true); return token.kind === 22 ? ts.findPrecedingToken(pos - 1, sourceFile) : token; @@ -85122,18 +85421,6 @@ var ts; } } } - var NodeSet = (function () { - function NodeSet() { - this.map = ts.createMap(); - } - NodeSet.prototype.add = function (node) { - this.map.set(String(ts.getNodeId(node)), node); - }; - NodeSet.prototype.some = function (pred) { - return ts.forEachEntry(this.map, pred) || false; - }; - return NodeSet; - }()); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -85193,6 +85480,8 @@ var ts; return ts.getModuleInstanceState(s) !== 1; case 237: return ts.hasModifier(s, 2048); + default: + return false; } } function sliceAfter(arr, value) { @@ -85363,7 +85652,7 @@ var ts; default: return; } - return { + return insertBefore && { insertBefore: insertBefore, returnType: getReturnType(containingFunction) }; @@ -86078,7 +86367,7 @@ var ts; } } function hasCallContext(usageContext) { - return usageContext && usageContext.callContexts; + return !!usageContext && !!usageContext.callContexts; } })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); @@ -86105,7 +86394,7 @@ var ts; var namespace = ts.getNamespaceDeclarationNode(node); var opts = context.program.getCompilerOptions(); var variations = []; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, undefined, node.moduleSpecifier, context.preferences))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(undefined, undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)))); } @@ -86211,8 +86500,9 @@ var ts; } 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)); + var type = propertyDeclaration.type; + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); } function getActionForAddMissingInitializer(context, propertyDeclaration) { var checker = context.program.getTypeChecker(); @@ -86538,14 +86828,14 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, 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); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { @@ -86561,8 +86851,8 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, undefined, info.moduleSpecifier, preferences)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -86599,6 +86889,56 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + 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 token = ts.getTokenAtPosition(sourceFile, pos, false); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var refactor; (function (refactor) { @@ -86738,7 +87078,8 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; - for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var start2 = start; + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { var errors_1 = checkNode(statement); @@ -86876,7 +87217,7 @@ var ts; } break; } - if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { case 233: case 234: @@ -87091,7 +87432,7 @@ var ts; case 156: return "'set " + scope.name.getText() + "'"; default: - ts.Debug.assertNever(scope); + throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { @@ -87482,7 +87823,8 @@ var ts; } prevMember = member; } - ts.Debug.assert(prevMember !== undefined); + if (prevMember === undefined) + return ts.Debug.fail(); return prevMember; } function getNodeToInsertConstantBefore(node, scope) { @@ -87507,13 +87849,9 @@ var ts; ts.Debug.assert(ts.isSwitchStatement(curr.parent.parent)); return curr.parent.parent; } - ts.Debug.assert(prevStatement !== undefined); - return prevStatement; - } - if (curr === scope) { - ts.Debug.fail("Didn't encounter a block-like before encountering scope"); - break; + return ts.Debug.assertDefined(prevStatement); } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); } } function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { @@ -87619,7 +87957,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_19 = function (i) { + var _loop_21 = 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; @@ -87655,7 +87993,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_19(i); + _loop_21(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -87843,22 +88181,23 @@ var ts; node.getEnd() <= ts.textSpanEnd(span); } function isExtractableExpression(node) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 272: return false; } switch (node.kind) { case 9: - return node.parent.kind !== 243 && - node.parent.kind !== 247; + return parent.kind !== 243 && + parent.kind !== 247; case 203: case 179: case 181: return false; case 71: - return node.parent.kind !== 181 && - node.parent.kind !== 247 && - node.parent.kind !== 251; + return parent.kind !== 181 && + parent.kind !== 247 && + parent.kind !== 251; } return true; } @@ -87941,7 +88280,7 @@ var ts; var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, ts.isParameter(declaration)); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } - function isConvertableName(name) { + function isConvertibleName(name) { return ts.isIdentifier(name) || ts.isStringLiteral(name); } function isAcceptedDeclaration(node) { @@ -87967,7 +88306,7 @@ var ts; var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); var meaning = 28 | 32 | 64; if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) - || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; var name = declaration.name.text; var startWithUnderscore = startsWithUnderscore(name); @@ -88025,7 +88364,9 @@ var ts; if (!constructor.body) return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; - var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); }); + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { + return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; var accessorName = ts.createIdentifier(fieldName.text); @@ -88047,7 +88388,7 @@ var ts; var refactorName = "Move to a new file"; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { - if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; @@ -88055,46 +88396,50 @@ var ts; getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === refactorName); var statements = ts.Debug.assertDefined(getStatementsToMove(context)); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - function getFirstAndLastStatementToMove(context) { + function getRangeToMove(context) { var file = context.file; var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); var statements = file.statements; var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); if (startNodeIndex === -1) return undefined; - if (range.pos > statements[startNodeIndex].getStart(file)) + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return [statements[startNodeIndex]]; + } + if (range.pos > startStatement.getStart(file)) return undefined; var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); } - function doChange(oldFile, program, toMove, changes, host) { + function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); var extension = ts.extensionFromPath(oldFile.fileName); var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; - changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); } function getStatementsToMove(context) { - var statements = context.file.statements; - var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; var all = []; var ranges = []; - var rangeToMove = statements.slice(first, afterLast); ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { for (var i = start; i < afterEnd; i++) all.push(rangeToMove[i]); ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); }); - return { all: all, ranges: ranges }; + return all.length === 0 ? undefined : { all: all, ranges: ranges }; } function isPureImport(node) { switch (node.kind) { @@ -88103,7 +88448,7 @@ var ts; case 242: return !ts.hasModifier(node, 1); case 213: - return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, true); }); + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, true); }); default: return false; } @@ -88122,26 +88467,26 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { deleteMovedStatements(oldFile, toMove.ranges, changes); return toMove.all; } var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, preferences); if (importsFromNewFile) { changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); } function deleteMovedStatements(sourceFile, moved, changes) { for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { - var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last; - changes.deleteNodeRange(sourceFile, first_1, last_3); + var _a = moved_1[_i], first_1 = _a.first, last_2 = _a.last; + changes.deleteNodeRange(sourceFile, first_1, last_2); } } function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { @@ -88154,10 +88499,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_20 = function (sourceFile) { + var _loop_22 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_21 = function (statement) { + var _loop_23 = function (statement) { forEachImportInStatement(statement, function (importNode) { var shouldMove = function (name) { var symbol = ts.isBindingElement(name.parent) @@ -88174,12 +88519,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_21(statement); + _loop_23(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_20(sourceFile); + _loop_22(sourceFile); } } function moduleSpecifierFromImport(i) { @@ -88206,7 +88551,7 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { @@ -88217,13 +88562,13 @@ var ts; imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { path = ts.ensurePathIsNonModuleName(path); if (useEs6Imports) { var specifiers = imports.map(function (i) { return ts.createImportSpecifier(undefined, ts.createIdentifier(i)); }); - return ts.makeImportIfNecessary(defaultImport, specifiers, path); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, preferences); } else { ts.Debug.assert(!defaultImport); @@ -88322,7 +88667,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -88353,7 +88698,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -88618,11 +88963,11 @@ var ts; case 236: case 235: case 242: - return undefined; + return ts.emptyArray; case 215: return ts.Debug.fail(); default: - ts.Debug.assertNever(decl); + return ts.Debug.assertNever(decl); } } function createExportAssignment(name) { @@ -88813,7 +89158,7 @@ var ts; var value = 0; for (; moreDigits; state.decodingIndex++) { if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return; + return undefined; } var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); moreDigits = (currentByte & 32) !== 0; @@ -89222,8 +89567,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); @@ -89515,11 +89860,11 @@ var ts; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); - return file && file.version; + return (file && file.version); }; HostCache.prototype.getScriptSnapshot = function (path) { var file = this.getHostFileInformation(path); - return file && file.scriptSnapshot; + return (file && file.scriptSnapshot); }; return HostCache; }()); @@ -89606,7 +89951,7 @@ var ts; this.cancellationToken = cancellationToken; } CancellationTokenObject.prototype.isCancellationRequested = function () { - return this.cancellationToken && this.cancellationToken.isCancellationRequested(); + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { @@ -89710,7 +90055,7 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { return; } var newSettings = hostCache.compilationSettings(); @@ -89773,7 +90118,7 @@ var ts; var entry = hostCache.getEntryByPath(path); return entry ? !ts.isString(entry) : - (host.fileExists && host.fileExists(fileName)); + (!!host.fileExists && host.fileExists(fileName)); } function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); @@ -89849,7 +90194,7 @@ var ts; function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName, preferences, cancellationToken); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), getCanonicalFileName, preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -90103,11 +90448,13 @@ var ts; return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); @@ -90128,7 +90475,7 @@ var ts; var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, startPos, false); if (node === sourceFile) { - return; + return undefined; } switch (node.kind) { case 184: @@ -90143,7 +90490,7 @@ var ts; case 71: break; default: - return; + return undefined; } var nodeForStartPos = node; while (true) { @@ -90292,7 +90639,7 @@ var ts; ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); default: - ts.Debug.fail(); + return ts.Debug.fail(); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -90349,7 +90696,8 @@ var ts; descriptor = descriptors[i]; } } - ts.Debug.assert(descriptor !== undefined); + if (descriptor === undefined) + return ts.Debug.fail(); if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { continue; } @@ -90566,10 +90914,11 @@ var ts; var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, false); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { - tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); - if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { return undefined; } + tokenAtLocation = preceding; } if (tokenAtLocation.flags & 4194304) { return undefined; @@ -90601,6 +90950,7 @@ var ts; } function spanInNode(node) { if (node) { + var parent = node.parent; switch (node.kind) { case 213: return spanInVariableDeclaration(node.declarationList.declarations[0]); @@ -90679,7 +91029,7 @@ var ts; case 225: return spanInNode(node.statement); case 149: - return spanInNodeArray(node.parent.decorators); + return spanInNodeArray(parent.decorators); case 179: case 180: return spanInBindingPattern(node); @@ -90722,7 +91072,7 @@ var ts; node.kind === 203 || node.kind === 269 || node.kind === 270) && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } if (node.kind === 199) { @@ -90738,7 +91088,7 @@ var ts; } } if (ts.isExpressionNode(node)) { - switch (node.parent.kind) { + switch (parent.kind) { case 217: return spanInPreviousNode(node); case 149: @@ -90805,12 +91155,13 @@ var ts; if (variableDeclaration.parent.parent.kind === 220) { return spanInNode(variableDeclaration.parent.parent); } + var parent = variableDeclaration.parent; if (ts.isBindingPattern(variableDeclaration.name)) { return spanInBindingPattern(variableDeclaration.name); } if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1) || - variableDeclaration.parent.parent.kind === 221) { + parent.parent.kind === 221) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -91292,7 +91643,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = (function (_super) { @@ -91533,9 +91885,11 @@ var ts; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); var result = ""; for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { @@ -91884,7 +92238,7 @@ var ts; function ThrottledOperations(host, logger) { this.host = host; this.pendingTimeouts = ts.createMap(); - this.logger = logger.hasLevel(server.LogLevel.verbose) && logger; + this.logger = logger.hasLevel(server.LogLevel.verbose) ? logger : undefined; } ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { var pendingTimeout = this.pendingTimeouts.get(operationId); @@ -92485,15 +92839,15 @@ var ts; } var set = ts.createMap(); var unique = 0; - for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { - var v = arr1_1[_i]; + for (var _i = 0, _a = arr1; _i < _a.length; _i++) { + var v = _a[_i]; if (set.get(v) !== true) { set.set(v, true); unique++; } } - for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { - var v = arr2_1[_a]; + for (var _b = 0, _c = arr2; _b < _c.length; _b++) { + var v = _c[_b]; var isSet = set.get(v); if (isSet === undefined) { return false; @@ -92756,11 +93110,11 @@ var ts; }; Project.prototype.getScriptKind = function (fileName) { var info = this.getOrCreateScriptInfoAndAttachToProject(fileName); - return info && info.scriptKind; + return (info && info.scriptKind); }; Project.prototype.getScriptVersion = function (filename) { var info = this.getOrCreateScriptInfoAndAttachToProject(filename); - return info && info.getLatestVersion(); + return (info && info.getLatestVersion()); }; Project.prototype.getScriptSnapshot = function (filename) { var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename); @@ -92993,9 +93347,7 @@ var ts; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); - if (!scriptInfo) { - ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' is missing."); - } + ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' is missing."; }); return scriptInfo; }); }; @@ -93065,6 +93417,7 @@ var ts; if (info && (info.isScriptOpen() || !requireOpen)) { return this.containsScriptInfo(info); } + return false; }; Project.prototype.isRoot = function (info) { return this.rootFilesMap && this.rootFilesMap.get(info.path) === info; @@ -93342,7 +93695,7 @@ var ts; } var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_22 = function (globalPluginName) { + var _loop_24 = function (globalPluginName) { if (!globalPluginName) return "continue"; if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) @@ -93353,7 +93706,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_22(globalPluginName); + _loop_24(globalPluginName); } } }; @@ -93756,7 +94109,7 @@ var ts; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, - hasMixedContent: function (x) { return x.hasMixedContent; }, + hasMixedContent: function (x) { return !!x.hasMixedContent; }, }; function findProjectByName(projectName, projects) { for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { @@ -93828,10 +94181,11 @@ var ts; if (this.host.realpath) { this.realpathToScriptInfos = ts.createMultiMap(); } - this.currentDirectory = this.host.getCurrentDirectory(); + this.currentDirectory = server.toNormalizedPath(this.host.getCurrentDirectory()); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); - this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation && - ts.ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)); + this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation + ? ts.ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)) + : undefined; this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); if (this.typesMapLocation) { this.loadTypesMap(); @@ -93847,7 +94201,7 @@ var ts; hostInfo: "Unknown host", extraFileExtensions: [] }; - this.documentRegistry = ts.createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.currentDirectory); + this.documentRegistry = ts.createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this); var watchLogLevel = this.logger.hasLevel(server.LogLevel.verbose) ? ts.WatchLogLevel.Verbose : this.logger.loggingEnabled() ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None; var log = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return _this.logger.info(s); }) : ts.noop; @@ -93862,6 +94216,14 @@ var ts; ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); }; + ProjectService.prototype.setDocument = function (key, path, sourceFile) { + var info = ts.Debug.assertDefined(this.getScriptInfoForPath(path)); + info.cacheSourceFile = { key: key, sourceFile: sourceFile }; + }; + ProjectService.prototype.getDocument = function (key, path) { + var info = this.getScriptInfoForPath(path); + return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : undefined; + }; ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { this.ensureProjectStructuresUptoDate(); }; @@ -94016,7 +94378,7 @@ var ts; } return scriptInfo.getDefaultProject(); } - return scriptInfo && !scriptInfo.isOrphan() && scriptInfo.getDefaultProject(); + return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined; }; ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { this.ensureProjectStructuresUptoDate(); @@ -94140,7 +94502,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_23 = function (inferredProject) { + var _loop_25 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -94152,7 +94514,7 @@ var ts; }; for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_23(inferredProject); + _loop_25(inferredProject); } } return project; @@ -94528,7 +94890,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject && project.getConfigFilePath(); + var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; return server.getBaseConfigFileName(configFilePath) || "other"; } function convertTypeAcquisition(_a) { @@ -94735,7 +95097,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_24 = function (project) { + var _loop_26 = function (project) { if (project.languageServiceEnabled && !project.isOrphan() && !project.getCompilerOptions().preserveSymlinks && @@ -94751,7 +95113,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_24(project); + _loop_26(project); } } } @@ -94794,7 +95156,7 @@ var ts; if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; } - info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, path); + info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path); this.filenameToScriptInfo.set(info.path, info); if (!openedByClient) { this.watchClosedScriptInfo(info); @@ -94996,13 +95358,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_25 = function (proj) { - var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); + var _loop_27 = function (proj) { + var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_25(proj); + _loop_27(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -95093,7 +95455,8 @@ var ts; }; ProjectService.prototype.applySafeList = function (proj) { var _this = this; - var rootFiles = proj.rootFiles, typeAcquisition = proj.typeAcquisition; + var rootFiles = proj.rootFiles; + var typeAcquisition = proj.typeAcquisition; ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); if (typeAcquisition.enable === false) { return []; @@ -95102,7 +95465,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_26 = function (name) { + var _loop_28 = 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]; @@ -95117,7 +95480,7 @@ var ts; } } if (rule.exclude) { - var _loop_28 = function (exclude) { + var _loop_30 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -95140,7 +95503,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_28(exclude); + _loop_30(exclude); } } else { @@ -95155,11 +95518,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_26(name); + _loop_28(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_27 = function (i) { + var _loop_29 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -95193,7 +95556,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_27(i); + _loop_29(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -95364,8 +95727,8 @@ var ts; return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; } function formatConfigFileDiag(diag, includeFileName) { - var start = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start)); - var end = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length)); + var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start))); + 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.diagnosticCategoryName(diag); @@ -95791,6 +96154,7 @@ var ts; this.logger = opts.logger; this.canUseEvents = opts.canUseEvents; this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate; var throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = this.canUseEvents ? opts.eventHandler || (function (event) { return _this.defaultEventHandler(event); }) @@ -95862,7 +96226,7 @@ var ts; var _this = this; this.projectService.logger.info("got projects updated in background, updating diagnostics for " + openFiles); if (openFiles.length) { - if (!this.suppressDiagnosticEvents) { + if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { var checkList_1 = this.createCheckList(openFiles); this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, true); }); } @@ -96004,20 +96368,20 @@ var ts; return project.getLanguageService().getEncodedSemanticClassifications(file, args); }; Session.prototype.getProject = function (projectFileName) { - return projectFileName && this.projectService.findProject(projectFileName); + return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName); }; Session.prototype.getConfigFileAndProject = function (args) { var project = this.getProject(args.projectFileName); var file = server.toNormalizedPath(args.file); return { - configFile: project && project.hasConfigFile(file) && file, + configFile: project && project.hasConfigFile(file) ? file : undefined, project: project }; }; Session.prototype.getConfigFileDiagnostics = function (configFile, project, includeLinePosition) { var projectErrors = project.getAllProjectErrors(); var optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); - var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return diagnostic.file && diagnostic.file.fileName === configFile; }); + var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return !!diagnostic.file && diagnostic.file.fileName === configFile; }); return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, false); }); @@ -96030,8 +96394,8 @@ var ts; length: d.length, 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)) + startLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start))), + endLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length))) }); }); }; Session.prototype.getCompilerOptionsDiagnostics = function (args) { @@ -96167,21 +96531,21 @@ var ts; if (configFile) { return server.emptyArray; } - return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); + return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project; if (configFile) { - return this.getConfigFileDiagnostics(configFile, project, args.includeLinePosition); + return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); } - return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); + 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); + 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; @@ -96701,7 +97065,7 @@ var ts; }; Session.prototype.reload = function (args, reqSeq) { var file = server.toNormalizedPath(args.file); - var tempFileName = args.tmpfile && server.toNormalizedPath(args.tmpfile); + var tempFileName = args.tmpfile === undefined ? undefined : server.toNormalizedPath(args.tmpfile); var info = this.projectService.getScriptInfoForNormalizedPath(file); if (info) { this.changeSeq++; @@ -97573,6 +97937,7 @@ var ts; this.load(LineIndex.linesFromText(newText).lines); return this; } + return undefined; } else { var checkText = void 0; @@ -97912,8 +98277,7 @@ var ts; return ts.combinePaths(ts.combinePaths(cacheLocation, "typescript"), ts.versionMajorMinor); } default: - ts.Debug.fail("unsupported platform '" + process.platform + "'"); - return; + return ts.Debug.fail("unsupported platform '" + process.platform + "'"); } } function getNonWindowsCacheLocation(platformIsDarwin) { @@ -98262,6 +98626,7 @@ var ts; canUseEvents: true, suppressDiagnosticEvents: suppressDiagnosticEvents, syntaxOnly: syntaxOnly, + noGetErrOnBackgroundUpdate: noGetErrOnBackgroundUpdate, globalPlugins: globalPlugins, pluginProbeLocations: pluginProbeLocations, allowLocalPluginLoads: allowLocalPluginLoads, @@ -98283,7 +98648,7 @@ var ts; return _this; } IOSession.prototype.event = function (body, eventName) { - ts.Debug.assert(this.constructed, "Should only call `IOSession.prototype.event` on an initialized IOSession"); + ts.Debug.assert(!!this.constructed, "Should only call `IOSession.prototype.event` on an initialized IOSession"); if (this.canUseEvents && this.eventPort) { if (!this.eventSocket) { if (this.logger.hasLevel(server.LogLevel.verbose)) { @@ -98590,8 +98955,8 @@ var ts; var eventPort; { var str = server.findArgument("--eventPort"); - var v = str && parseInt(str); - if (!isNaN(v)) { + var v = str === undefined ? undefined : parseInt(str); + if (v !== undefined && !isNaN(v)) { eventPort = v; } } @@ -98619,6 +98984,7 @@ var ts; var suppressDiagnosticEvents = server.hasArgument("--suppressDiagnosticEvents"); var syntaxOnly = server.hasArgument("--syntaxOnly"); var telemetryEnabled = server.hasArgument(server.Arguments.EnableTelemetry); + var noGetErrOnBackgroundUpdate = server.hasArgument("--noGetErrOnBackgroundUpdate"); logger.info("Starting TS Server"); logger.info("Version: " + ts.version); logger.info("Arguments: " + process.argv.join(" ")); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index cbf39a2a48f..d0f46e74b44 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -460,7 +460,7 @@ declare namespace ts { flags: NodeFlags; decorators?: NodeArray; modifiers?: ModifiersArray; - parent?: Node; + parent: Node; } interface JSDocContainer { } @@ -525,12 +525,12 @@ declare namespace ts { } interface Decorator extends Node { kind: SyntaxKind.Decorator; - parent?: NamedDeclaration; + parent: NamedDeclaration; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; - parent?: DeclarationWithTypeParameters | InferTypeNode; + parent: DeclarationWithTypeParameters | InferTypeNode; name: Identifier; constraint?: TypeNode; default?: TypeNode; @@ -541,7 +541,7 @@ declare namespace ts { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; - type: TypeNode | undefined; + type?: TypeNode; } type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { @@ -553,7 +553,7 @@ declare namespace ts { type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; - parent?: VariableDeclarationList | CatchClause; + parent: VariableDeclarationList | CatchClause; name: BindingName; exclamationToken?: ExclamationToken; type?: TypeNode; @@ -561,12 +561,12 @@ declare namespace ts { } interface VariableDeclarationList extends Node { kind: SyntaxKind.VariableDeclarationList; - parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; + parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.Parameter; - parent?: SignatureDeclaration; + parent: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; name: BindingName; questionToken?: QuestionToken; @@ -575,7 +575,7 @@ declare namespace ts { } interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; - parent?: BindingPattern; + parent: BindingPattern; propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: BindingName; @@ -628,12 +628,12 @@ declare namespace ts { } interface ObjectBindingPattern extends Node { kind: SyntaxKind.ObjectBindingPattern; - parent?: VariableDeclaration | ParameterDeclaration | BindingElement; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; elements: NodeArray; } interface ArrayBindingPattern extends Node { kind: SyntaxKind.ArrayBindingPattern; - parent?: VariableDeclaration | ParameterDeclaration | BindingElement; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; elements: NodeArray; } type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; @@ -662,41 +662,41 @@ declare namespace ts { } interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; - parent?: ObjectTypeDeclaration; + parent: ObjectTypeDeclaration; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.MethodDeclaration; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassLikeDeclaration; + parent: ClassLikeDeclaration; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassLikeDeclaration; + parent: ClassLikeDeclaration; } interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ObjectTypeDeclaration; + parent: ObjectTypeDeclaration; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -730,7 +730,7 @@ declare namespace ts { } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; - parent?: SignatureDeclaration; + parent: SignatureDeclaration; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -959,15 +959,15 @@ declare namespace ts { } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; - parent?: TemplateExpression; + parent: TemplateExpression; } interface TemplateMiddle extends LiteralLikeNode { kind: SyntaxKind.TemplateMiddle; - parent?: TemplateSpan; + parent: TemplateSpan; } interface TemplateTail extends LiteralLikeNode { kind: SyntaxKind.TemplateTail; - parent?: TemplateSpan; + parent: TemplateSpan; } type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { @@ -977,7 +977,7 @@ declare namespace ts { } interface TemplateSpan extends Node { kind: SyntaxKind.TemplateSpan; - parent?: TemplateExpression; + parent: TemplateExpression; expression: Expression; literal: TemplateMiddle | TemplateTail; } @@ -991,7 +991,7 @@ declare namespace ts { } interface SpreadElement extends Expression { kind: SyntaxKind.SpreadElement; - parent?: ArrayLiteralExpression | CallExpression | NewExpression; + parent: ArrayLiteralExpression | CallExpression | NewExpression; expression: Expression; } /** @@ -1044,7 +1044,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent?: HeritageClause; + parent: HeritageClause; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1090,11 +1090,11 @@ declare namespace ts { type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxAttributes extends ObjectLiteralExpressionBase { - parent?: JsxOpeningLikeElement; + parent: JsxOpeningLikeElement; } interface JsxOpeningElement extends Expression { kind: SyntaxKind.JsxOpeningElement; - parent?: JsxElement; + parent: JsxElement; tagName: JsxTagNameExpression; typeArguments?: NodeArray; attributes: JsxAttributes; @@ -1113,38 +1113,38 @@ declare namespace ts { } interface JsxOpeningFragment extends Expression { kind: SyntaxKind.JsxOpeningFragment; - parent?: JsxFragment; + parent: JsxFragment; } interface JsxClosingFragment extends Expression { kind: SyntaxKind.JsxClosingFragment; - parent?: JsxFragment; + parent: JsxFragment; } interface JsxAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxAttribute; - parent?: JsxAttributes; + parent: JsxAttributes; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxSpreadAttribute; - parent?: JsxAttributes; + parent: JsxAttributes; expression: Expression; } interface JsxClosingElement extends Node { kind: SyntaxKind.JsxClosingElement; - parent?: JsxElement; + parent: JsxElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { kind: SyntaxKind.JsxExpression; - parent?: JsxElement | JsxAttributeLike; + parent: JsxElement | JsxAttributeLike; dotDotDotToken?: Token; expression?: Expression; } interface JsxText extends Node { kind: SyntaxKind.JsxText; containsOnlyWhiteSpaces: boolean; - parent?: JsxElement; + parent: JsxElement; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; interface Statement extends Node { @@ -1245,18 +1245,18 @@ declare namespace ts { } interface CaseBlock extends Node { kind: SyntaxKind.CaseBlock; - parent?: SwitchStatement; + parent: SwitchStatement; clauses: NodeArray; } interface CaseClause extends Node { kind: SyntaxKind.CaseClause; - parent?: CaseBlock; + parent: CaseBlock; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { kind: SyntaxKind.DefaultClause; - parent?: CaseBlock; + parent: CaseBlock; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; @@ -1267,7 +1267,7 @@ declare namespace ts { } interface ThrowStatement extends Statement { kind: SyntaxKind.ThrowStatement; - expression: Expression; + expression?: Expression; } interface TryStatement extends Statement { kind: SyntaxKind.TryStatement; @@ -1277,7 +1277,7 @@ declare namespace ts { } interface CatchClause extends Node { kind: SyntaxKind.CatchClause; - parent?: TryStatement; + parent: TryStatement; variableDeclaration?: VariableDeclaration; block: Block; } @@ -1317,7 +1317,7 @@ declare namespace ts { } interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassLikeDeclaration; + parent: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -1329,7 +1329,7 @@ declare namespace ts { } interface EnumMember extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.EnumMember; - parent?: EnumDeclaration; + parent: EnumDeclaration; name: PropertyName; initializer?: Expression; } @@ -1342,7 +1342,7 @@ declare namespace ts { type ModuleBody = NamespaceBody | JSDocNamespaceBody; interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ModuleDeclaration; - parent?: ModuleBody | SourceFile; + parent: ModuleBody | SourceFile; name: ModuleName; body?: ModuleBody | JSDocNamespaceDeclaration; } @@ -1354,11 +1354,11 @@ declare namespace ts { type JSDocNamespaceBody = Identifier | JSDocNamespaceDeclaration; interface JSDocNamespaceDeclaration extends ModuleDeclaration { name: Identifier; - body: JSDocNamespaceBody; + body?: JSDocNamespaceBody; } interface ModuleBlock extends Node, Statement { kind: SyntaxKind.ModuleBlock; - parent?: ModuleDeclaration; + parent: ModuleDeclaration; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; @@ -1369,18 +1369,18 @@ declare namespace ts { */ interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ImportEqualsDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { kind: SyntaxKind.ExternalModuleReference; - parent?: ImportEqualsDeclaration; - expression?: Expression; + parent: ImportEqualsDeclaration; + expression: Expression; } interface ImportDeclaration extends Statement { kind: SyntaxKind.ImportDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; importClause?: ImportClause; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier: Expression; @@ -1388,13 +1388,13 @@ declare namespace ts { type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; - parent?: ImportDeclaration; + parent: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; - parent?: ImportClause; + parent: ImportClause; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { @@ -1403,7 +1403,7 @@ declare namespace ts { } interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ @@ -1411,24 +1411,24 @@ declare namespace ts { } interface NamedImports extends Node { kind: SyntaxKind.NamedImports; - parent?: ImportClause; + parent: ImportClause; elements: NodeArray; } interface NamedExports extends Node { kind: SyntaxKind.NamedExports; - parent?: ExportDeclaration; + parent: ExportDeclaration; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; - parent?: NamedImports; + parent: NamedImports; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; - parent?: NamedExports; + parent: NamedExports; propertyName?: Identifier; name: Identifier; } @@ -1439,7 +1439,7 @@ declare namespace ts { */ interface ExportAssignment extends DeclarationStatement { kind: SyntaxKind.ExportAssignment; - parent?: SourceFile; + parent: SourceFile; isExportEquals?: boolean; expression: Expression; } @@ -1494,15 +1494,15 @@ declare namespace ts { type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; - parent?: HasJSDoc; - tags: NodeArray | undefined; - comment: string | undefined; + parent: HasJSDoc; + tags?: NodeArray; + comment?: string; } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; atToken: AtToken; tagName: Identifier; - comment: string | undefined; + comment?: string; } interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; @@ -1526,11 +1526,11 @@ declare namespace ts { } interface JSDocReturnTag extends JSDocTag { kind: SyntaxKind.JSDocReturnTag; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { kind: SyntaxKind.JSDocTypeTag; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { parent: JSDoc; @@ -1608,7 +1608,7 @@ declare namespace ts { container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNodeBase { - antecedents: FlowNode[]; + antecedents: FlowNode[] | undefined; } interface FlowAssignment extends FlowNodeBase { node: Expression | VariableDeclaration | BindingElement; @@ -1635,7 +1635,7 @@ declare namespace ts { } interface AmdDependency { path: string; - name: string; + name?: string; } interface SourceFile extends Declaration { kind: SyntaxKind.SourceFile; @@ -1644,7 +1644,7 @@ declare namespace ts { fileName: string; text: string; amdDependencies: ReadonlyArray; - moduleName: string; + moduleName?: string; referencedFiles: ReadonlyArray; typeReferenceDirectives: ReadonlyArray; languageVariant: LanguageVariant; @@ -1704,7 +1704,7 @@ declare namespace ts { fileExists(path: string): boolean; readFile(path: string): string | undefined; } - type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray) => void; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { @@ -1734,9 +1734,10 @@ declare namespace ts { emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. @@ -1793,7 +1794,7 @@ declare namespace ts { emitSkipped: boolean; /** Contains declaration emit diagnostics */ diagnostics: ReadonlyArray; - emittedFiles: string[]; + emittedFiles?: string[]; } interface TypeChecker { getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; @@ -1810,7 +1811,7 @@ declare namespace ts { getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; + typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; @@ -1846,7 +1847,7 @@ declare namespace ts { */ getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; - getTypeAtLocation(node: Node): Type; + getTypeAtLocation(node: Node): Type | undefined; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; @@ -1863,9 +1864,10 @@ declare namespace ts { getContextualType(node: Expression): Type | undefined; /** * returns unknownSignature in the case of an error. + * returns undefined if the node is not valid. * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. */ - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; @@ -2069,8 +2071,8 @@ declare namespace ts { interface Symbol { flags: SymbolFlags; escapedName: __String; - declarations?: Declaration[]; - valueDeclaration?: Declaration; + declarations: Declaration[]; + valueDeclaration: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; @@ -2172,15 +2174,15 @@ declare namespace ts { type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { flags: TypeFlags; - symbol?: Symbol; + symbol: Symbol; pattern?: DestructuringPattern; aliasSymbol?: Symbol; aliasTypeArguments?: Type[]; } interface LiteralType extends Type { value: string | number; - freshType?: LiteralType; - regularType?: LiteralType; + freshType: LiteralType; + regularType: LiteralType; } interface UniqueESSymbolType extends Type { symbol: Symbol; @@ -2215,18 +2217,18 @@ declare namespace ts { } /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[]; - outerTypeParameters: TypeParameter[]; - localTypeParameters: TypeParameter[]; - thisType: TypeParameter; + typeParameters: TypeParameter[] | undefined; + outerTypeParameters: TypeParameter[] | undefined; + localTypeParameters: TypeParameter[] | undefined; + thisType: TypeParameter | undefined; } type BaseType = ObjectType | IntersectionType; interface InterfaceTypeWithDeclaredMembers extends InterfaceType { declaredProperties: Symbol[]; declaredCallSignatures: Signature[]; declaredConstructSignatures: Signature[]; - declaredStringIndexInfo: IndexInfo; - declaredNumberIndexInfo: IndexInfo; + declaredStringIndexInfo?: IndexInfo; + declaredNumberIndexInfo?: IndexInfo; } /** * Type references (ObjectFlags.Reference). When a class or interface has type parameters or @@ -2277,11 +2279,11 @@ declare namespace ts { trueType: Type; falseType: Type; isDistributive: boolean; - inferTypeParameters: TypeParameter[]; + inferTypeParameters?: TypeParameter[]; outerTypeParameters?: TypeParameter[]; instantiations?: Map; - aliasSymbol: Symbol; - aliasTypeArguments: Type[]; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; } interface ConditionalType extends InstantiableType { root: ConditionalRoot; @@ -2359,6 +2361,11 @@ declare namespace ts { code: number; source?: string; } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; + } enum DiagnosticCategory { Warning = 0, Error = 1, @@ -2447,6 +2454,7 @@ declare namespace ts { sourceMap?: boolean; sourceRoot?: string; strict?: boolean; + strictAny?: boolean; strictFunctionTypes?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; @@ -2624,7 +2632,7 @@ declare namespace ts { packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { - readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; readonly failedLookupLocations: ReadonlyArray; } interface CompilerHost extends ModuleResolutionHost { @@ -2644,8 +2652,8 @@ declare namespace ts { /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; - getEnvironmentVariable?(name: string): string; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; } interface SourceMapRange extends TextRange { @@ -2657,6 +2665,7 @@ declare namespace ts { skipTrivia?: (pos: number) => number; } enum EmitFlags { + None = 0, SingleLine = 1, AdviseOnEmitNode = 2, NoSubstitution = 4, @@ -2710,7 +2719,7 @@ declare namespace ts { /** Resumes a suspended lexical environment, usually before visiting a function body. */ resumeLexicalEnvironment(): void; /** Ends a lexical environment, returning any declarations. */ - endLexicalEnvironment(): Statement[]; + endLexicalEnvironment(): Statement[] | undefined; /** Hoists a function declaration to the containing scope. */ hoistFunctionDeclaration(node: FunctionDeclaration): void; /** Hoists a variable declaration to the containing scope. */ @@ -2754,7 +2763,7 @@ declare namespace ts { /** Gets the transformed source files. */ transformed: T[]; /** Gets diagnostics for the transformation. */ - diagnostics?: Diagnostic[]; + diagnostics?: DiagnosticWithLocation[]; /** * Gets a substitute for a node, if one is available; otherwise, returns the original node. * @@ -2841,7 +2850,7 @@ declare namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -2954,13 +2963,13 @@ declare namespace ts { } } declare namespace ts { - const versionMajorMinor = "2.9"; + const versionMajorMinor = "3.0"; /** The version of the TypeScript compiler release */ const version: string; } declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): Diagnostic[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3014,7 +3023,7 @@ declare namespace ts { interface FileWatcher { close(): void; } - function getNodeMajorVersion(): number; + function getNodeMajorVersion(): number | undefined; let sys: System; } declare namespace ts { @@ -3041,8 +3050,8 @@ declare namespace ts { scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; - setText(text: string, start?: number, length?: number): void; - setOnError(onError: ErrorCallback): void; + setText(text: string | undefined, start?: number, length?: number): void; + setOnError(onError: ErrorCallback | undefined): void; setScriptTarget(scriptTarget: ScriptTarget): void; setLanguageVariant(variant: LanguageVariant): void; setTextPos(textPos: number): void; @@ -3062,15 +3071,15 @@ declare namespace ts { function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; - function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; - function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ function getShebang(text: string): string | undefined; - function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -3079,12 +3088,12 @@ declare namespace ts { function textSpanContainsPosition(span: TextSpan, position: number): boolean; function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined; function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined; function createTextSpan(start: number, length: number): TextSpan; function createTextSpanFromBounds(start: number, end: number): TextSpan; function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; @@ -3100,7 +3109,7 @@ declare namespace ts { * Vn. */ function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration; + function getTypeParameterOwner(d: Declaration): Declaration | undefined; type ParameterPropertyDeclaration = ParameterDeclaration & { parent: ConstructorDeclaration; name: Identifier; @@ -3122,6 +3131,8 @@ declare namespace ts { }, errors?: Push): void; function getOriginalNode(node: Node): Node; function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + function getOriginalNode(node: Node | undefined): Node | undefined; + function getOriginalNode(node: Node | undefined, nodeTest: (node: Node | undefined) => node is T): T | undefined; /** * Gets a value indicating whether a node originated in the parse tree. * @@ -3142,7 +3153,7 @@ declare namespace ts { * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. * @returns The original parse tree node if found; otherwise, undefined. */ - function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; + function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; /** * Remove extra underscore from escaped identifier text content. * @@ -3160,7 +3171,7 @@ declare namespace ts { */ function unescapeIdentifier(id: string): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; - function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName; /** * Gets the JSDoc parameter tags for the node if present. * @@ -3442,7 +3453,7 @@ declare namespace ts { */ function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; - function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined; /** * Parse json text into SyntaxTree and return node and parse errors if any * @param fileName @@ -3488,7 +3499,7 @@ declare namespace ts { getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; } interface PerModuleNameCache { - get(directory: string): ResolvedModuleWithFailedLookupLocations; + get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; @@ -3570,7 +3581,7 @@ declare namespace ts { function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; function createTypeQueryNode(exprName: EntityName): TypeQueryNode; function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createTypeLiteralNode(members: ReadonlyArray): TypeLiteralNode; + function createTypeLiteralNode(members: ReadonlyArray | undefined): TypeLiteralNode; function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; @@ -3609,23 +3620,23 @@ declare namespace ts { function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; - function createPropertyAccess(expression: Expression, name: string | Identifier): PropertyAccessExpression; + function createPropertyAccess(expression: Expression, name: string | Identifier | undefined): PropertyAccessExpression; function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; - function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): CallExpression; function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; - function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray, template: TemplateLiteral): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; - function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray, template: TemplateLiteral): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; function createParen(expression: Expression): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; @@ -3655,15 +3666,15 @@ declare namespace ts { function createTemplateTail(text: string): TemplateTail; function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; function createYield(expression?: Expression): YieldExpression; - function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; + function createYield(asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function createSpread(expression: Expression): SpreadElement; function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; - function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; - function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; function createOmittedExpression(): OmittedExpression; - function createExpressionWithTypeArguments(typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; - function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; function createAsExpression(expression: Expression, type: TypeNode): AsExpression; function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; @@ -3690,8 +3701,8 @@ declare namespace ts { function updateFor(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - function createForOf(awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; - function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createForOf(awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; function createContinue(label?: string | Identifier): ContinueStatement; function updateContinue(node: ContinueStatement, label: Identifier | undefined): ContinueStatement; function createBreak(label?: string | Identifier): BreakStatement; @@ -3715,8 +3726,8 @@ declare namespace ts { function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; - function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; @@ -3734,7 +3745,7 @@ declare namespace ts { function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; - function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function createNamespaceImport(name: Identifier): NamespaceImport; @@ -3743,7 +3754,7 @@ declare namespace ts { function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; @@ -3873,16 +3884,16 @@ declare namespace ts { */ function setCommentRange(node: T, range: TextRange): T; function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[]): T; + function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T; function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; + function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; function moveSyntheticComments(node: T, original: Node): T; /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number | undefined; /** * Sets the constant value to emit for an expression. */ @@ -3918,7 +3929,7 @@ declare namespace ts { * @param test A callback to execute to verify the Node is valid. * @param lift An optional callback to execute to lift a NodeArray into a valid Node. */ - function visitNode(node: T, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; /** * Visits a Node using the supplied visitor, possibly returning a new Node in its place. * @@ -3927,7 +3938,7 @@ declare namespace ts { * @param test A callback to execute to verify the Node is valid. * @param lift An optional callback to execute to lift a NodeArray into a valid Node. */ - function visitNode(node: T | undefined, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; /** * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. * @@ -3937,7 +3948,7 @@ declare namespace ts { * @param start An optional value indicating the starting offset at which to start visiting. * @param count An optional value indicating the maximum number of nodes to visit. */ - function visitNodes(nodes: NodeArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; /** * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. * @@ -3957,7 +3968,7 @@ declare namespace ts { * Starts a new lexical environment and visits a parameter list, suspending the lexical * environment upon completion. */ - function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; /** * Resumes a suspended lexical environment and visits a function body, ending the lexical * environment and merging hoisted declarations upon completion. @@ -4006,7 +4017,7 @@ declare namespace ts { function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string; function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' @@ -4201,11 +4212,11 @@ declare namespace ts { /** If provided would be used to write log about compilation */ trace?(s: string): void; /** If provided is used to get the environment variable */ - getEnvironmentVariable?(name: string): string; + getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; /** Used to watch changes in source files, missing files needed to update the program or config file */ watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ @@ -4355,8 +4366,8 @@ declare namespace ts { getLeadingTriviaWidth(sourceFile?: SourceFile): number; getFullText(sourceFile?: SourceFile): string; getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node; - getLastToken(sourceFile?: SourceFile): Node; + getFirstToken(sourceFile?: SourceFile): Node | undefined; + getLastToken(sourceFile?: SourceFile): Node | undefined; forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; } interface Identifier { @@ -4444,7 +4455,7 @@ declare namespace ts { referencedFiles: FileReference[]; typeReferenceDirectives: FileReference[]; importedFiles: FileReference[]; - ambientExternalModules: string[]; + ambientExternalModules?: string[]; isLibFile: boolean; } interface HostCancellationToken { @@ -4477,7 +4488,7 @@ declare namespace ts { fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; - getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getDirectories?(directoryName: string): string[]; /** @@ -4497,9 +4508,10 @@ declare namespace ts { } interface LanguageService { cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(fileName: string): Diagnostic[]; - getSuggestionDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. @@ -4511,24 +4523,24 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails; - getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol; - getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; - getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; + getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; - getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - findReferences(fileName: string, position: number): ReferencedSymbol[]; - getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; @@ -4539,9 +4551,9 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan | undefined; toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; @@ -4559,7 +4571,7 @@ declare namespace ts { organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; - getProgram(): Program; + getProgram(): Program | undefined; dispose(): void; } interface CombinedCodeFixScope { @@ -4662,7 +4674,7 @@ declare namespace ts { } interface CombinedCodeActions { changes: ReadonlyArray; - commands: ReadonlyArray | undefined; + commands?: ReadonlyArray; } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { @@ -4712,8 +4724,8 @@ declare namespace ts { */ interface RefactorEditInfo { edits: FileTextChanges[]; - renameFilename: string | undefined; - renameLocation: number | undefined; + renameFilename?: string; + renameLocation?: number; commands?: CodeActionCommand[]; } interface TextInsertion { @@ -4834,7 +4846,7 @@ declare namespace ts { containerName: string; } interface DefinitionInfoAndBoundSpan { - definitions: ReadonlyArray; + definitions?: ReadonlyArray; textSpan: TextSpan; } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { @@ -4880,13 +4892,13 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; textSpan: TextSpan; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - tags: JSDocTagInfo[]; + displayParts?: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; } interface RenameInfo { canRename: boolean; - localizedErrorMessage: string; + localizedErrorMessage?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; @@ -4938,7 +4950,7 @@ declare namespace ts { interface CompletionEntry { name: string; kind: ScriptElementKind; - kindModifiers: string; + kindModifiers?: string; sortText: string; insertText?: string; /** @@ -4956,8 +4968,8 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - tags: JSDocTagInfo[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; source?: SymbolDisplayPart[]; } @@ -5270,12 +5282,12 @@ declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string; function getDefaultCompilerOptions(): CompilerOptions; function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; - function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnly?: boolean): LanguageService; /** * Get the path of the default library files (lib.d.ts) as distributed with the typescript @@ -5433,7 +5445,7 @@ declare namespace ts.server { startGroup(): void; endGroup(): void; msg(s: string, type?: Msg): void; - getLogFileName(): string; + getLogFileName(): string | undefined; } enum Msg { Err = "Err", @@ -5458,7 +5470,7 @@ declare namespace ts.server { function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; function asNormalizedPath(fileName: string): NormalizedPath; interface NormalizedPathMap { - get(path: NormalizedPath): T; + get(path: NormalizedPath): T | undefined; set(path: NormalizedPath, value: T): void; contains(path: NormalizedPath): boolean; remove(path: NormalizedPath): void; @@ -6851,7 +6863,7 @@ declare namespace ts.server.protocol { } interface CompletionEntryIdentifier { name: string; - source: string; + source?: string; } /** * Completion entry details request; value of command field is @@ -6891,7 +6903,7 @@ declare namespace ts.server.protocol { /** * Optional modifiers for the kind (such as 'public'). */ - kindModifiers: string; + kindModifiers?: string; /** * A string that is used for comparing completion items so that they can be ordered. This * is often the same as the name but may be different in certain circumstances. @@ -6948,11 +6960,11 @@ declare namespace ts.server.protocol { /** * Documentation strings for the symbol. */ - documentation: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; /** * JSDoc tags for the symbol. */ - tags: JSDocTagInfo[]; + tags?: JSDocTagInfo[]; /** * The associated code actions for this entry */ @@ -7727,15 +7739,15 @@ declare namespace ts.server { close(fileExists?: boolean): void; getSnapshot(): IScriptSnapshot; private ensureRealPath; - getFormatCodeSettings(): FormatCodeSettings; - getPreferences(): UserPreferences; + getFormatCodeSettings(): FormatCodeSettings | undefined; + getPreferences(): UserPreferences | undefined; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; detachFromProject(project: Project): void; detachAllProjects(): void; getDefaultProject(): Project; registerFileUpdate(): void; - setOptions(formatSettings: FormatCodeSettings, preferences: UserPreferences): void; + setOptions(formatSettings: FormatCodeSettings, preferences: UserPreferences | undefined): void; getLatestVersion(): string; saveTo(fileName: string): void; reloadFromFile(tempFileName?: NormalizedPath): void; @@ -7763,7 +7775,7 @@ declare namespace ts.server { interface ITypingsInstaller { isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptionsWithProject): Promise; - enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray): void; + enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray | undefined): void; attach(projectService: ProjectService): void; onProjectClosed(p: Project): void; readonly globalTypingsCacheLocation: string | undefined; @@ -7856,7 +7868,7 @@ declare namespace ts.server { private getOrCreateScriptInfoAndAttachToProject; getScriptKind(fileName: string): ScriptKind; getScriptVersion(filename: string): string; - getScriptSnapshot(filename: string): IScriptSnapshot; + getScriptSnapshot(filename: string): IScriptSnapshot | undefined; getCancellationToken(): HostCancellationToken; getCurrentDirectory(): string; getDefaultLibFileName(): string; @@ -7865,7 +7877,7 @@ declare namespace ts.server { readFile(fileName: string): string | undefined; fileExists(file: string): boolean; resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[]; - getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations; + getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists(path: string): boolean; getDirectories(path: string): string[]; @@ -7890,7 +7902,7 @@ declare namespace ts.server { abstract getTypeAcquisition(): TypeAcquisition; protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; getExternalFiles(): SortedReadonlyArray; - getSourceFile(path: Path): SourceFile; + getSourceFile(path: Path): SourceFile | undefined; close(): void; private detachScriptInfoIfNotRoot; isClosed(): boolean; @@ -7920,7 +7932,7 @@ declare namespace ts.server { private addMissingFileWatcher; private isWatchedMissingFile; getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; - getScriptInfo(uncheckedFileName: string): ScriptInfo; + getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; @@ -8066,7 +8078,7 @@ declare namespace ts.server { readonly info: OpenFileInfo; } interface ProjectInfoTypeAcquisitionData { - readonly enable: boolean; + readonly enable: boolean | undefined; readonly include: boolean; readonly exclude: boolean; } @@ -8127,7 +8139,6 @@ declare namespace ts.server { syntaxOnly?: boolean; } class ProjectService { - private readonly documentRegistry; /** * Container of all known scripts */ @@ -8152,7 +8163,7 @@ declare namespace ts.server { /** * Open files: with value being project root path, and key being Path of the file that is open */ - readonly openFiles: Map; + readonly openFiles: Map; /** * Map of open files that are opened without complete path but have projectRoot as current directory */ @@ -8176,7 +8187,7 @@ declare namespace ts.server { private safelist; private legacySafelist; private pendingProjectUpdates; - readonly currentDirectory: string; + readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; readonly host: ServerHost; readonly logger: Logger; @@ -8204,8 +8215,8 @@ declare namespace ts.server { private delayUpdateProjectGraphs; setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void; findProject(projectName: string): Project | undefined; - getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project; - getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo; + getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined; + getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined; /** * Ensures the project structures are upto date * This means, @@ -8289,18 +8300,18 @@ declare namespace ts.server { private getOrCreateSingleInferredProjectIfEnabled; private getOrCreateSingleInferredWithoutProjectRoot; private createInferredProject; - getScriptInfo(uncheckedFileName: string): ScriptInfo; + getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; private watchClosedScriptInfo; private stopWatchingScriptInfo; getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { fileExists(path: string): boolean; - }): ScriptInfo; + }): ScriptInfo | undefined; private getOrCreateScriptInfoWorker; /** * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred */ - getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; - getScriptInfoForPath(fileName: Path): ScriptInfo; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; + getScriptInfoForPath(fileName: Path): ScriptInfo | undefined; setHostConfiguration(args: protocol.ConfigureRequestArguments): void; closeLog(): void; /** @@ -8391,6 +8402,7 @@ declare namespace ts.server { suppressDiagnosticEvents?: boolean; syntaxOnly?: boolean; throttleWaitMilliseconds?: number; + noGetErrOnBackgroundUpdate?: boolean; globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; @@ -8410,6 +8422,7 @@ declare namespace ts.server { protected canUseEvents: boolean; private suppressDiagnosticEvents?; private eventHandler; + private readonly noGetErrOnBackgroundUpdate?; constructor(opts: SessionOptions); private sendRequestCompletedEvent; private defaultEventHandler; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index ae049cd4143..baca307efa3 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1325,6 +1325,7 @@ var ts; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; @@ -1633,7 +1634,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "2.9"; + ts.versionMajorMinor = "3.0"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1937,7 +1938,7 @@ var ts; return result; } } - Debug.fail(); + return Debug.fail(); } ts.findMap = findMap; function contains(array, value, equalityComparer) { @@ -2055,11 +2056,6 @@ var ts; return array; } ts.sameMap = sameMap; - /** - * Flattens an array containing a mix of array or non-array elements. - * - * @param array The array to flatten. - */ function flatten(array) { var result; if (array) { @@ -2079,12 +2075,6 @@ var ts; return result; } ts.flatten = flatten; - /** - * Maps an array. If the mapped value is an array, it is spread into the result. - * - * @param array The array to map. - * @param mapfn The callback used to map the result into one or more values. - */ function flatMap(array, mapfn) { var result; if (array) { @@ -2207,13 +2197,6 @@ var ts; }; } ts.singleIterator = singleIterator; - /** - * Maps contiguous spans of values with the same key. - * - * @param array The array to map. - * @param keyfn A callback used to select the key for an element. - * @param mapfn A callback used to map a contiguous chunk of values to a single value. - */ function spanMap(array, keyfn, mapfn) { var result; if (array) { @@ -2331,12 +2314,6 @@ var ts; } return result; } - /** - * Deduplicates an unsorted array. - * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. - * @param comparer An optional `Comparer` used to sort entries before comparison, though the - * result will remain in the original order in `array`. - */ function deduplicate(array, equalityComparer, comparer) { return !array ? undefined : array.length === 0 ? [] : @@ -2345,9 +2322,6 @@ var ts; deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; - /** - * Deduplicates an array that has already been sorted. - */ function deduplicateSorted(array, comparer) { if (!array) return undefined; @@ -2490,14 +2464,6 @@ var ts; return result; } ts.sum = sum; - /** - * Appends a value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param value The value to append to the array. If `value` is `undefined`, nothing is - * appended. - */ function append(to, value) { if (value === undefined) return to; @@ -2514,16 +2480,6 @@ var ts; function toOffset(array, offset) { return offset < 0 ? array.length + offset : offset; } - /** - * Appends a range of value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - * @param start The offset in `from` at which to start copying values. - * @param end The offset in `from` at which to stop copying values (non-inclusive). - */ function addRange(to, from, start, end) { if (from === undefined || from.length === 0) return to; @@ -2539,23 +2495,6 @@ var ts; return to; } ts.addRange = addRange; - /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - */ - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; /** * @return Whether the value was added. */ @@ -2853,7 +2792,7 @@ var ts; var arg = args_1[_a]; for (var p in arg) { if (hasProperty(arg, p)) { - t[p] = arg[p]; + t[p] = arg[p]; // TODO: GH#23368 } } } @@ -3012,10 +2951,10 @@ var ts; if (value !== undefined && test(value)) return value; if (value && typeof value.kind === "number") { - Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); } else { - Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } } ts.cast = cast; @@ -3101,7 +3040,7 @@ var ts; } ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { - baseIndex = baseIndex || 0; + if (baseIndex === void 0) { baseIndex = 0; } return text.replace(/{(\d+)}/g, function (_match, index) { return Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; @@ -3409,7 +3348,9 @@ var ts; return compareValues(a ? 1 : 0, b ? 1 : 0); } ts.compareBooleans = compareBooleans; - function compareMessageText(text1, text2) { + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; while (text1 && text2) { // We still have both chains. var string1 = isString(text1) ? text1 : text1.messageText; @@ -3446,6 +3387,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -3464,7 +3413,7 @@ var ts; } ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { - return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { @@ -3989,7 +3938,7 @@ var ts; /** * Matches any single directory segment unless it is the last segment and a .min.js file * Breakdown: - * [^./] # matches everything up to the first . character (excluding directory seperators) + * [^./] # matches everything up to the first . character (excluding directory separators) * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension */ singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", @@ -4051,7 +4000,7 @@ var ts; var subpattern = ""; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); - var lastComponent = lastOrUndefined(components); + var lastComponent = last(components); if (usage !== "exclude" && lastComponent === "**") { return undefined; } @@ -4277,11 +4226,11 @@ var ts; return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { @@ -4487,7 +4436,8 @@ var ts; } Debug.fail = fail; function assertDefined(value, message) { - assert(value !== undefined && value !== null, message); + if (value === undefined || value === null) + return fail(message); return value; } Debug.assertDefined = assertDefined; @@ -4671,10 +4621,7 @@ var ts; */ function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); - if (ext !== undefined) { - return ext; - } - Debug.fail("File " + path + " has unknown extension."); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; function isAnySupportedFileExtension(path) { @@ -5118,6 +5065,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: this is used as if it's certainly defined in many places. ts.sys = (function () { // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual // byte order mark from the specified encoding. Using any other byte order mark does @@ -5299,6 +5247,7 @@ var ts; return watchDirectoryRecursively(directoryName, callback); } watchDirectory(directoryName, callback); + return undefined; // TODO: GH#18217 }; } function createNonPollingWatchFile() { @@ -5330,7 +5279,7 @@ var ts; var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" var fileName = !ts.isString(relativeFileName) - ? undefined + ? undefined // TODO: GH#18217 : ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); @@ -5579,6 +5528,7 @@ var ts; switch (entryKind) { case 0 /* File */: return stat.isFile(); case 1 /* Directory */: return stat.isDirectory(); + default: return false; } } catch (e) { @@ -6274,7 +6224,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -6602,6 +6552,8 @@ var ts; _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Enable_strict_checking_of_any_type: diag(6200, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_any_type_6200", "Enable strict checking of 'any' type."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -6629,7 +6581,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -6710,6 +6662,7 @@ var ts; Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -6779,6 +6732,7 @@ var ts; Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), }; })(ts || (ts = {})); var ts; @@ -7485,8 +7439,9 @@ var ts; } ts.isIdentifierText = isIdentifierText; // Creates a scanner over a (possibly unspecified) range of a piece of text. - function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; // Current position (end position of text of current token) var pos; // end of text @@ -7942,7 +7897,7 @@ var ts; var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); - // Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator if (ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (separatorAllowed) { @@ -8758,7 +8713,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function packageIdToString(_a) { var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; @@ -8896,6 +8851,27 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Appends a range of value to begin of an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; /** * Determine if the given comment is a triple-slash * @@ -8985,7 +8961,7 @@ var ts; */ function getEmitFlags(node) { var emitNode = node.emitNode; - return emitNode && emitNode.flags; + return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { @@ -9019,7 +8995,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return node.text; } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { @@ -9127,7 +9103,7 @@ var ts; case 212 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block - return parentNode && !ts.isFunctionLike(parentNode); + return !ts.isFunctionLike(parentNode); } return false; } @@ -9219,7 +9195,7 @@ var ts; case 8 /* NumericLiteral */: return escapeLeadingUnderscores(name.text); case 146 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; + return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: ts.Debug.assertNever(name); } @@ -9233,6 +9209,8 @@ var ts; return entityNameToString(name.left) + "." + entityNameToString(name.right); case 184 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); } } ts.entityNameToString = entityNameToString; @@ -9441,7 +9419,7 @@ var ts; // falls through case 145 /* QualifiedName */: case 184 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: + case 99 /* ThisKeyword */: { var parent = node.parent; if (parent.kind === 164 /* TypeQuery */) { return false; @@ -9490,6 +9468,7 @@ var ts; // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } + } } return false; } @@ -9685,15 +9664,16 @@ var ts; return ts.filter(objectLiteral.properties, function (property) { if (property.kind === 269 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); - return key === propName || (key2 && key2 === propName); + return key === propName || (!!key2 && key2 === propName); } + return false; }); } ts.getPropertyAssignment = getPropertyAssignment; function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { var expression = tsConfigSourceFile.statements[0].expression; - return ts.isObjectLiteralExpression(expression) && expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); } } ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; @@ -9716,10 +9696,11 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 273 /* SourceFile */); while (true) { node = node.parent; if (!node) { - return undefined; + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { case 146 /* ComputedPropertyName */: @@ -9924,20 +9905,22 @@ var ts; ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node, parent, grandparent); + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; function nodeOrChildIsDecorated(node, parent, grandparent) { - return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { case 234 /* ClassDeclaration */: - return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 case 153 /* MethodDeclaration */: case 156 /* SetAccessor */: - return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; } } ts.childIsDecorated = childIsDecorated; @@ -10081,15 +10064,15 @@ var ts; } ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536 /* JavaScriptFile */); + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; function isInJsonFile(node) { - return node && !!(node.flags & 16777216 /* JsonFile */); + return !!node && !!(node.flags & 16777216 /* JsonFile */); } ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { - return node && !!(node.flags & 2097152 /* JSDoc */); + return !!node && !!(node.flags & 2097152 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; function isJSDocIndexSignature(node) { @@ -10360,7 +10343,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 243 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 243 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { @@ -10397,16 +10380,18 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ && - node.expression.right; + node.expression.operatorToken.kind === 58 /* EqualsToken */ + ? node.expression.right + : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ && - node.expression.right.right; + node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + ? node.expression.right.right + : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { @@ -10420,15 +10405,14 @@ var ts; } } function getSingleVariableOfVariableStatement(node) { - return ts.isVariableStatement(node) && - node.declarationList.declarations.length > 0 && - node.declarationList.declarations[0]; + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } function getNestedModuleDeclaration(node) { - return node.kind === 238 /* ModuleDeclaration */ && + return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 238 /* ModuleDeclaration */ && - node.body; + node.body.kind === 238 /* ModuleDeclaration */ + ? node.body + : undefined; } function getJSDocCommentsAndTags(hostNode) { var result; @@ -10517,12 +10501,12 @@ var ts; ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { var last = ts.lastOrUndefined(s.parameters); - return last && isRestParameter(last); + return !!last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || type && type.kind === 284 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 284 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -10660,9 +10644,10 @@ var ts; switch (name.kind) { case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - if (ts.isDeclaration(name.parent)) { - return name.parent.name === name; + case 8 /* NumericLiteral */: { + var parent = name.parent; + if (ts.isDeclaration(parent)) { + return parent.name === name; } else if (ts.isQualifiedName(name.parent)) { var tag = name.parent.parent; @@ -10672,6 +10657,7 @@ var ts; var binExp = name.parent.parent; return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; } + } default: return false; } @@ -10876,7 +10862,7 @@ var ts; */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); - return name && isDynamicName(name); + return !!name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -11169,7 +11155,7 @@ var ts; } ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; function createDiagnosticCollection() { - var nonFileDiagnostics = []; + var nonFileDiagnostics = []; // See GH#19873 var filesWithDiagnostics = []; var fileDiagnostics = ts.createMap(); var hasReadNonFileDiagnostics = false; @@ -11187,7 +11173,7 @@ var ts; if (diagnostic.file) { diagnostics = fileDiagnostics.get(diagnostic.file.fileName); if (!diagnostics) { - diagnostics = []; + diagnostics = []; // See GH#19873 fileDiagnostics.set(diagnostic.file.fileName, diagnostics); ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); } @@ -11334,7 +11320,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); + linePos = output.length - s.length + ts.last(lineStartsOfS); } } } @@ -11509,7 +11495,7 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { @@ -11517,6 +11503,7 @@ var ts; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 var firstAccessor; var secondAccessor; var getAccessor; @@ -11713,13 +11700,13 @@ var ts; // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; } } } @@ -11888,7 +11875,7 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 206 /* ExpressionWithTypeArguments */ && + if (ts.isExpressionWithTypeArguments(node) && node.parent.token === 85 /* ExtendsKeyword */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -12858,7 +12845,7 @@ var ts; // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) ts.localizedDiagnosticMessages = JSON.parse(fileContents); } - catch (e) { + catch (_a) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); } @@ -12987,6 +12974,7 @@ var ts; return !!node.name; // A 'name' property should always be a DeclarationName. } ts.isNamedDeclaration = isNamedDeclaration; + // TODO: GH#18217 This is often used as if it returns a defined result function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -13912,7 +13900,6 @@ var ts; // Identifiers /* @internal */ function isGeneratedIdentifier(node) { - // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; @@ -14610,8 +14597,10 @@ var ts; ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times function hasJSDocNodes(node) { - return !!node.jsDoc && node.jsDoc.length > 0; + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; /** True if has type node attached to it. */ @@ -15278,6 +15267,7 @@ var ts; // becoming detached from any SourceFile). It is recommended that this SourceFile not // be used once 'update' is called on it. function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. // We will manually port the flag to the new source file. @@ -15403,6 +15393,7 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); @@ -15604,6 +15595,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -16124,7 +16116,7 @@ var ts; case 14 /* JsxChildren */: return true; } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); @@ -16213,6 +16205,8 @@ var ts; return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; case 14 /* JsxChildren */: return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; } } function isVariableDeclaratorListTerminator() { @@ -16544,6 +16538,7 @@ var ts; case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; + default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` } } // Parses a comma-delimited list of elements @@ -16676,7 +16671,7 @@ var ts; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } @@ -16915,7 +16910,7 @@ var ts; if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); + signature.parameters = parseParameterList(flags); // TODO: GH#18217 if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { signature.type = parseTypeOrTypePredicate(); return signature.type !== undefined; @@ -17077,7 +17072,7 @@ var ts; if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return true; } - var idToken; + var idToken = false; // Eat up all modifiers, but hold on to the last one in case it is actually an identifier while (ts.isModifierKind(token())) { idToken = true; @@ -17200,7 +17195,7 @@ var ts; parseExpected(19 /* OpenParenToken */); node.type = parseType(); if (!node.type) { - return undefined; + return undefined; // TODO: GH#18217 } parseExpected(20 /* CloseParenToken */); return finishNode(node); @@ -17532,7 +17527,7 @@ var ts; } function parseTypeWorker(noConditionalTypes) { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162 /* FunctionType */); + return parseFunctionOrConstructorType(162 /* FunctionType */); // TODO: GH#18217 } if (token() === 94 /* NewKeyword */) { return parseFunctionOrConstructorType(163 /* ConstructorType */); @@ -18499,7 +18494,7 @@ var ts; badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -19554,6 +19549,7 @@ var ts; missing.modifiers = node.modifiers; return finishNode(missing); } + return undefined; // TODO: GH#18217 } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { @@ -19897,7 +19893,7 @@ var ts; return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. - ts.Debug.fail("Should not have attempted to parse class member declaration."); + return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 204 /* ClassExpression */); @@ -19945,14 +19941,12 @@ var ts; } function parseHeritageClause() { var tok = token(); - if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { - var node = createNode(267 /* HeritageClause */); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; + ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(267 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); } function parseExpressionWithTypeArguments() { var node = createNode(206 /* ExpressionWithTypeArguments */); @@ -20384,8 +20378,8 @@ var ts; PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } var content = sourceText; - start = start || 0; var end = length === undefined ? content.length : start + length; length = end - start; ts.Debug.assert(start >= 0); @@ -20715,7 +20709,7 @@ var ts; var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -20795,7 +20789,7 @@ var ts; while (parseOptional(23 /* DotToken */)) { var prop = createNode(184 /* PropertyAccessExpression */, node.pos); prop.expression = node; - prop.name = parseJSDocIdentifierName(); + prop.name = parseJSDocIdentifierName(); // TODO: GH#18217 node = finishNode(prop); } return node; @@ -20935,7 +20929,7 @@ var ts; var child = tryParseChildTag(target); if (child && child.kind === 292 /* JSDocParameterTag */ && target !== 4 /* CallbackParameter */ && - (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { // TODO: GH#18217 return false; } return child; @@ -21581,7 +21575,7 @@ var ts; context.pragmas = ts.createMap(); for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { var pragma = pragmas_1[_i]; - if (context.pragmas.has(pragma.name)) { + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 var currentValue = context.pragmas.get(pragma.name); if (currentValue instanceof Array) { currentValue.push(pragma.args); @@ -21610,6 +21604,7 @@ var ts; var referencedFiles_1 = context.referencedFiles; var typeReferenceDirectives_1 = context.typeReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } @@ -21626,10 +21621,7 @@ var ts; break; } case "amd-dependency": { - context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { - var _b = _a.arguments, name = _b.name, path = _b.path; - return ({ name: name, path: path }); - }); + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 break; } case "amd-module": { @@ -21652,7 +21644,7 @@ var ts; case "ts-check": { // _last_ of either nocheck or check in a file is the "winner" ts.forEach(ts.toArray(entryOrList), function (entry) { - if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 context.checkJsDirective = { enabled: key === "ts-check", end: entry.range.end, @@ -22036,7 +22028,7 @@ var ts; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); // TODO: GH#18217 } /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @@ -22836,6 +22828,7 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -22877,7 +22870,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -23261,7 +23254,7 @@ var ts; // We do that by making an anonymous type literal symbol, and then setting the function // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. - var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 addDeclarationToSymbol(symbol, node, 131072 /* Signature */); var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); @@ -23507,6 +23500,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -24036,7 +24039,7 @@ var ts; (symbol.exports || (symbol.exports = ts.createSymbolTable())); // Declare the method/property var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); // TODO: GH#18217 var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); @@ -24066,7 +24069,8 @@ var ts; } else { var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); - ts.Debug.assert(!!s && !!s.exports); + if (!s || !s.exports) + return ts.Debug.fail(); return action(e.name, s.exports.get(e.name.escapedText)); } } @@ -24207,7 +24211,7 @@ var ts; } function bindTypeParameter(node) { if (ts.isJSDocTemplateTag(node.parent)) { - var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 if (container_1) { if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); @@ -24227,7 +24231,7 @@ var ts; declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } else { - bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { @@ -24237,7 +24241,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -24255,22 +24259,22 @@ var ts; (node.kind === 237 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304 /* Ambient */) && - (node.kind !== 213 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -24286,8 +24290,8 @@ var ts; ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { return isExportsOrModuleExportsOrAlias(sourceFile, node) || @@ -25282,11 +25286,11 @@ var ts; } function visitSymbol(symbol) { if (!symbol) { - return; + return false; } var symbolId = ts.getSymbolId(symbol); if (visitedSymbols[symbolId]) { - return; + return false; } visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { @@ -25308,6 +25312,7 @@ var ts; visitSymbol(entity); } }); + return false; } } } @@ -25321,7 +25326,7 @@ var ts; ts.trace = trace; /* @internal */ function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; + return !!compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; function withPackageId(packageId, r) { @@ -25501,7 +25506,6 @@ var ts; } } function secondaryLookup() { - var resolvedFile; var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations @@ -25509,7 +25513,7 @@ var ts; trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); + var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -25582,7 +25586,7 @@ var ts; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; + return undefined; // TODO: GH#18217 } var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { @@ -25694,7 +25698,7 @@ var ts; result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; default: - ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -25947,7 +25951,7 @@ var ts; var originalPath = void 0; if (!compilerOptions.preserveSymlinks && resolvedValue) { originalPath = resolvedValue.path; - var path = realPath(resolved_1.value.path, host, traceEnabled); + var path = realPath(resolvedValue.path, host, traceEnabled); if (path === originalPath) { originalPath = undefined; } @@ -26066,7 +26070,7 @@ var ts; function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); @@ -26105,7 +26109,7 @@ var ts; } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, ext: ext }; + return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ @@ -26495,6 +26499,7 @@ var ts; var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var strictAny = ts.getStrictOptionValue(compilerOptions, "strictAny"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; @@ -26527,9 +26532,10 @@ var ts; location = ts.getParseTreeNode(location); return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); }, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, @@ -26541,8 +26547,8 @@ var ts; getBaseTypes: getBaseTypes, getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node ? getTypeFromTypeNode(node) : unknownType; }, getParameterType: getTypeAtPosition, @@ -26569,8 +26575,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getShorthandAssignmentValueSymbol(node) : undefined; }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, getExportSymbolOfSymbol: function (symbol) { @@ -26580,8 +26586,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; }, signatureToString: function (signature, enclosingDeclaration, flags, kind) { @@ -26611,41 +26617,41 @@ var ts; getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, - getContextualTypeForArgumentAtIndex: function (node, argIndex) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); }, - getContextualTypeForJsxAttribute: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxAttributeLike); + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); apparentArgumentCount = theArgumentCount; var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; apparentArgumentCount = undefined; return res; }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); }, - isValidPropertyAccessForCompletions: function (node, type, property) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); return !!node && isValidPropertyAccessForCompletions(node, type, property); }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); return declaration ? getSignatureFromDeclaration(declaration) : undefined; }, isImplementationOfOverload: function (node) { @@ -26657,7 +26663,8 @@ var ts; var links = getSymbolLinks(symbol); if (!links.immediateTarget) { var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); } return links.immediateTarget; @@ -26668,13 +26675,13 @@ var ts; getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); return node ? isOptionalParameter(node) : false; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, @@ -26720,8 +26727,8 @@ var ts; node = ts.getParseTreeNode(node); return node && tryGetThisTypeAt(node); }, - getTypeArgumentConstraint: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file) { @@ -27028,6 +27035,7 @@ var ts; typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); }, buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); }, buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { @@ -27041,12 +27049,12 @@ var ts; buildParameterDisplay: function (symbol, writer, enclosing, flags) { var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 }, buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 }, buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); @@ -27059,13 +27067,13 @@ var ts; buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { var printer = ts.createPrinter({ removeComments: true }); var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); - var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; - var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; // TODO: GH#18217 + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); // TODO: GH#18217 printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); }, buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { var printer = ts.createPrinter({ removeComments: true }); - var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); // TODO: GH#18217 printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); }, buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { @@ -27077,7 +27085,7 @@ var ts; } var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 } }; function emitTextWriterWrapper(underlying) { @@ -27164,7 +27172,7 @@ var ts; } var jsxPragma = file_1.pragmas.get("jsx"); if (jsxPragma) { - var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file_1.localJsxFactory) { return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText; @@ -27459,7 +27467,7 @@ var ts; if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); @@ -27534,7 +27542,8 @@ var ts; break; } // ForIn/ForOf case - use site should not be used in expression part - return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); } function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { return !!ts.findAncestor(usage, function (current) { @@ -27560,6 +27569,7 @@ var ts; } } } + return false; }); } } @@ -27838,7 +27848,7 @@ var ts; if (!result) { if (nameNotFoundMessage) { if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && @@ -27890,7 +27900,7 @@ var ts; if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 241 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } } @@ -27918,7 +27928,7 @@ var ts; if (decl.kind === 147 /* TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 } } } @@ -27945,7 +27955,7 @@ var ts; // No static member is present. // Check if we're in an instance method and look for a relevant instance member. if (location === container && !ts.hasModifier(location, 32 /* Static */)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); return true; @@ -27958,11 +27968,11 @@ var ts; } function checkAndReportErrorForExtendingInterface(errorLocation) { var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); - if (isError) { + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; + return false; } /** * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, @@ -28038,7 +28048,8 @@ var ts; ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 237 /* EnumDeclaration */) ? d : undefined; }); - ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); @@ -28056,7 +28067,7 @@ var ts; * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. */ function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { switch (node.kind) { @@ -28191,12 +28202,13 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 } } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { var name = specifier.propertyName || specifier.name; @@ -28261,6 +28273,7 @@ var ts; return getNodeLinks(expression).resolvedSymbol; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { case 242 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); @@ -28277,6 +28290,8 @@ var ts; return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 241 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); } } /** @@ -28287,11 +28302,10 @@ var ts; if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || (symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); } function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); - return shouldResolve ? resolveAlias(symbol) : symbol; + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); @@ -28299,7 +28313,8 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -28332,7 +28347,8 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); if (node.kind === 248 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); @@ -28431,7 +28447,7 @@ var ts; } } else { - ts.Debug.assertNever(name, "Unknown entity name kind."); + throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -28492,7 +28508,7 @@ var ts; return ambientModule; } var currentSourceFile = ts.getSourceFileOfNode(location); - var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -28566,8 +28582,6 @@ var ts; /*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)); errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } - // 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) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } @@ -28899,7 +28913,7 @@ var ts; // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -28927,6 +28941,11 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } @@ -28934,7 +28953,7 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; @@ -29008,7 +29027,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // Any meaning of a module symbol is always accessible via an `import` type return { accessibility: 0 /* Accessible */ @@ -29059,6 +29078,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -29144,7 +29166,7 @@ var ts; var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { - var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); @@ -29152,6 +29174,7 @@ var ts; } } function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); function signatureToStringWorker(writer) { var sigOutput; @@ -29164,15 +29187,16 @@ var ts; var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 return writer; } } function typeToString(type, enclosingDeclaration, flags, writer) { - if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; } + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } 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"); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); @@ -29185,6 +29209,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } return flags & 9469291 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { @@ -29201,7 +29226,7 @@ var ts; var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; - return result; + return result; // TODO: GH#18217 }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); @@ -29249,7 +29274,7 @@ var ts; function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, - flags: flags, + flags: flags || 0 /* None */, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, @@ -29264,7 +29289,7 @@ var ts; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { return ts.createKeywordTypeNode(119 /* AnyKeyword */); @@ -29354,9 +29379,10 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); @@ -29375,7 +29401,7 @@ var ts; if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } - return undefined; + return undefined; // TODO: GH#18217 } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { @@ -29406,7 +29432,7 @@ var ts; if (type.flags & 4194304 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } - ts.Debug.fail("Should be unreachable."); + return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -29480,7 +29506,7 @@ var ts; if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively - (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } } @@ -29532,7 +29558,7 @@ var ts; return ts.createTupleTypeNode([]); } context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && @@ -29655,7 +29681,7 @@ var ts; var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(propertySymbol.declarations); + var decl = ts.first(propertySymbol.declarations); var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); if (name && context.tracker.trackSymbol) { context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); @@ -29718,7 +29744,7 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } @@ -29795,7 +29821,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration @@ -29823,12 +29849,12 @@ var ts; } } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { - context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { - chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } else { @@ -29858,7 +29884,7 @@ var ts; // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; @@ -30035,6 +30061,7 @@ var ts; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); @@ -30115,7 +30142,7 @@ var ts; return "default"; } if (symbol.declarations && symbol.declarations.length) { - if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { + if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { // TODO: GH#18217 var file_3 = ts.getDeclarationOfKind(symbol, 273 /* SourceFile */); if (!file_3 || !context.tracker.moduleResolverHost) { if (context.tracker.trackReferencedAmbientModule) { @@ -30123,7 +30150,7 @@ var ts; if (ts.length(ambientDecls)) { for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { var decl = ambientDecls_1[_i]; - context.tracker.trackReferencedAmbientModule(decl); + context.tracker.trackReferencedAmbientModule(decl); // TODO: GH#18217 } } } @@ -30329,22 +30356,22 @@ var ts; } function hasType(target, propertyName) { if (propertyName === 0 /* Type */) { - return getSymbolLinks(target).type; + return !!getSymbolLinks(target).type; } if (propertyName === 2 /* DeclaredType */) { - return getSymbolLinks(target).declaredType; + return !!getSymbolLinks(target).declaredType; } if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return target.resolvedBaseConstructorType; + return !!target.resolvedBaseConstructorType; } if (propertyName === 3 /* ResolvedReturnType */) { - return target.resolvedReturnType; + return !!target.resolvedReturnType; } if (propertyName === 4 /* ResolvedBaseConstraint */) { var bc = target.resolvedBaseConstraint; - return bc && bc !== circularConstraintType; + return !!bc && bc !== circularConstraintType; } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -30354,7 +30381,7 @@ var ts; return resolutionResults.pop(); } function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { case 231 /* VariableDeclaration */: case 232 /* VariableDeclarationList */: @@ -30366,8 +30393,7 @@ var ts; default: return true; } - }); - return node && node.parent; + }).parent; } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 @@ -30480,7 +30506,7 @@ var ts; } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - var nameType = isLate && checkComputedPropertyName(name); + var nameType = isLate ? checkComputedPropertyName(name) : undefined; var text = isLate ? getLateBoundNameFromType(nameType) : isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : ts.getTextOfPropertyName(name); @@ -30742,7 +30768,7 @@ var ts; definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 /* Nullable */ | 16777216 /* ContainsWideningType */)); }) ? constructorTypes : types; + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 /* Nullable */ | 16777216 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); @@ -30818,7 +30844,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + if (!lastElement || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. @@ -30838,6 +30864,8 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } return pattern.kind === 179 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); @@ -30956,7 +30984,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } else { - ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); } if (!popTypeResolution()) { type = reportCircularityError(symbol); @@ -31158,16 +31186,18 @@ var ts; function getTargetType(type) { return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. function hasBaseType(type, checkBase) { return check(type); function check(type) { if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); + return target === checkBase || ts.some(getBaseTypes(target), check); } else if (type.flags & 262144 /* Intersection */) { - return ts.forEach(type.types, check); + return ts.some(type.types, check); } + return false; } } // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. @@ -31183,7 +31213,7 @@ var ts; // Return the outer type parameters of a node or undefined if the node has no outer type parameters. function getOuterTypeParameters(node, includeThisTypes) { while (true) { - node = node.parent; + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead if (!node) { return undefined; } @@ -31264,7 +31294,7 @@ var ts; } if (type.flags & 1081344 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } @@ -31396,7 +31426,7 @@ var ts; // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a // partial instantiation of the members without the base types fully resolved - type.members = undefined; + type.members = undefined; // TODO: GH#18217 } return type.resolvedBaseTypes = [baseType]; } @@ -31414,8 +31444,8 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return type.flags & (65536 /* Object */ | 134217728 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || - type.flags & 262144 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return !!(type.flags & (65536 /* Object */ | 134217728 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 262144 /* Intersection */) && !ts.some(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -31605,7 +31635,7 @@ var ts; if (declaration.kind === 237 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; memberTypeList.push(memberType); } @@ -31720,7 +31750,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) && + return (node.kind === 154 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -31805,7 +31835,7 @@ var ts; */ function hasLateBindableName(node) { var name = ts.getNameOfDeclaration(node); - return name && isLateBindableName(name); + return !!name && isLateBindableName(name); } /** * Indicates whether a declaration has a dynamic name that cannot be late-bound. @@ -31829,6 +31859,7 @@ var ts; if (type.flags & 96 /* StringOrNumberLiteral */) { return ts.escapeLeadingUnderscores("" + type.value); } + return ts.Debug.fail(); } /** * Adds a declaration to a late-bound dynamic member. This performs the same function for @@ -31846,8 +31877,7 @@ var ts; symbol.declarations.push(member); } if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } } @@ -32075,7 +32105,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); @@ -32147,6 +32177,7 @@ var ts; if (unionSignatures.length > 1) { var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); thisParameter = createSymbolWithType(signature.thisParameter, thisType); } @@ -32412,7 +32443,7 @@ var ts; return type.declaration.typeParameter.constraint; } function isMappedTypeWithKeyofConstraintDeclaration(type) { - var constraintDeclaration = getConstraintDeclarationForMappedType(type); + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 return constraintDeclaration.kind === 174 /* TypeOperator */ && constraintDeclaration.operator === 128 /* KeyOfKeyword */; } @@ -32454,7 +32485,7 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); } function isGenericMappedType(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -33061,14 +33092,6 @@ var ts; } return minTypeArgumentCount; } - /** - * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined - * when a default type is supplied, a new array will be created and returned. - * - * @param typeArguments The supplied type arguments. - * @param typeParameters The requested type parameters. - * @param minTypeArgumentCount The minimum number of required type arguments. - */ function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { @@ -33103,7 +33126,7 @@ var ts; var hasLiteralTypes = false; var minArgumentCount = 0; var thisParameter = void 0; - var hasThisParameter = void 0; + var hasThisParameter = false; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && @@ -33190,7 +33213,7 @@ var ts; } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 } else if (classType) { return classType; @@ -33233,7 +33256,7 @@ var ts; return node.name.kind === 146 /* ComputedPropertyName */ && traverse(node.name); default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); } } } @@ -33243,7 +33266,7 @@ var ts; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { var decl = symbol.declarations[i]; - var node = ts.isPropertyAccessExpression(decl) ? ts.getAssignedJavascriptInitializer(decl) : decl; + var node = ts.isPropertyAccessExpression(decl) ? ts.getAssignedJavascriptInitializer(decl) : decl; // TODO: GH#18217 if (!ts.isFunctionLike(node)) continue; // Don't include signature if node is the implementation of an overloaded function. A node is considered @@ -33333,9 +33356,10 @@ var ts; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + var type = getTypeOfSymbol(ts.last(signature.parameters)); if (ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { - return type.typeArguments[0]; + var t = type.typeArguments[0]; + return strictAny && t.flags & 1 /* Any */ ? unknownType : t; } } return anyType; @@ -33394,7 +33418,7 @@ var ts; // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 154 /* Constructor */ || signature.declaration.kind === 158 /* ConstructSignature */; + var isConstructor = signature.declaration.kind === 154 /* Constructor */ || signature.declaration.kind === 158 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -33676,7 +33700,8 @@ var ts; var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); if (referenceType || assignedType) { - return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -33727,7 +33752,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return node.flags & 2097152 /* JSDoc */ && node.kind === 161 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 161 /* TypeReference */; } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -33774,7 +33799,7 @@ var ts; var indexed = getTypeFromTypeNode(typeArgs[0]); var target = getTypeFromTypeNode(typeArgs[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); } return anyType; } @@ -33911,7 +33936,7 @@ var ts; return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { - return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. @@ -34315,16 +34340,19 @@ var ts; // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); if (includes & 16384 /* Never */) { return neverType; } - if (includes & 1 /* Any */) { - return includes & 33554432 /* Wildcard */ ? wildcardType : anyType; + if (includes & 33554432 /* Wildcard */) { + return wildcardType; + } + if (!strictAny && includes & 1 /* Any */) { + return anyType; + } + if (!strictNullChecks && includes & 12288 /* Nullable */) { + return includes & 4096 /* Undefined */ ? undefinedType : nullType; } if (includes & 2 /* String */ && includes & 32 /* StringLiteral */ || includes & 4 /* Number */ && includes & 64 /* NumberLiteral */ || @@ -34334,6 +34362,9 @@ var ts; if (includes & 67108864 /* EmptyObject */ && !(includes & 65536 /* Object */)) { typeSet.push(emptyObjectType); } + if (typeSet.length === 0) { + return anyType; + } if (typeSet.length === 1) { return typeSet[0]; } @@ -34441,7 +34472,7 @@ var ts; break; } } - return links.resolvedType; + return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { var type = createType(1048576 /* IndexedAccess */); @@ -34530,12 +34561,12 @@ var ts; var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - t.stringIndexInfo && !t.numberIndexInfo; + !!t.stringIndexInfo && !t.numberIndexInfo; } return false; } function isMappedTypeToNever(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; } function getSimplifiedType(type) { return type.flags & 1048576 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; @@ -34720,7 +34751,7 @@ var ts; result.mapper = mapper; result.combinedMapper = combinedMapper; result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } function getTrueTypeFromConditionalType(type) { @@ -34849,7 +34880,7 @@ var ts; } } } - return links.resolvedType; + return links.resolvedType; // TODO: GH#18217 } function resolveImportSymbolType(node, links, symbol, meaning) { links.resolvedSymbol = symbol; @@ -35004,7 +35035,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -35138,7 +35171,7 @@ var ts; case 71 /* Identifier */: case 145 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 default: return unknownType; } @@ -35361,21 +35394,21 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_3; })) { - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { case 173 /* ThisType */: - return tp.isThisType; + return !!tp.isThisType; case 71 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; case 164 /* TypeQuery */: return true; } - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -35510,9 +35543,9 @@ var ts; case 153 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); case 183 /* ObjectLiteralExpression */: - return ts.forEach(node.properties, isContextSensitive); + return ts.some(node.properties, isContextSensitive); case 182 /* ArrayLiteralExpression */: - return ts.forEach(node.elements, isContextSensitive); + return ts.some(node.elements, isContextSensitive); case 200 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); @@ -35524,13 +35557,17 @@ var ts; case 190 /* ParenthesizedExpression */: return isContextSensitive(node.expression); case 262 /* JsxAttributes */: - return ts.forEach(node.properties, isContextSensitive); - case 261 /* JsxAttribute */: + return ts.some(node.properties, isContextSensitive); + case 261 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. - return node.initializer && isContextSensitive(node.initializer); - case 264 /* JsxExpression */: + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 264 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) - return node.expression && isContextSensitive(node.expression); + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } } return false; } @@ -35540,7 +35577,7 @@ var ts; return false; } // Functions with any parameters that lack type annotations are context sensitive. - if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } if (node.kind !== 192 /* ArrowFunction */) { @@ -35552,7 +35589,8 @@ var ts; } } // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return node.body.kind === 212 /* Block */ ? false : isContextSensitive(node.body); + var body = node.body; + return body.kind === 212 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -35692,6 +35730,7 @@ var ts; var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { @@ -35713,7 +35752,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -35805,8 +35844,8 @@ var ts; function isEmptyObjectType(type) { return type.flags & 65536 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 134217728 /* NonPrimitive */ ? true : - type.flags & 131072 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 262144 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + type.flags & 131072 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 262144 /* Intersection */ ? !ts.some(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -35881,7 +35920,7 @@ var ts; if (s & 1024 /* UniqueESSymbol */ || t & 1024 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { - if (s & 1 /* Any */) + if (s & 1 /* Any */ && (!strictAny || source === unknownType || t & 65536 /* Object */ && isEmptyObjectType(target))) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because @@ -35949,7 +35988,7 @@ var ts; errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); // TODO: GH#18217 } // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement if (headMessage && errorNode && !result && source.symbol) { @@ -36023,6 +36062,7 @@ var ts; * * Ternary.False if they are not related. */ function isRelatedTo(source, target, reportErrors, headMessage) { + if (reportErrors === void 0) { reportErrors = false; } if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 8388608 /* FreshLiteral */) { source = source.regularType; } @@ -36216,7 +36256,8 @@ var ts; // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. - ts.Debug.assert(!!errorNode); + if (!errorNode) + return { value: ts.Debug.fail() }; if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. @@ -36230,8 +36271,9 @@ var ts; var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; - if (ts.isIdentifier(propDeclaration.name)) { - suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); } } if (suggestion !== undefined) { @@ -36896,7 +36938,7 @@ var ts; // in the context of the target signature before checking the relationship. Ideally we'd do // this regardless of the number of signatures, but the potential costs are prohibitive due // to the quadratic nature of the logic below. - var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); } else { @@ -36992,7 +37034,7 @@ var ts; if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } // if T is related to U. - return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 } if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; @@ -37112,7 +37154,7 @@ var ts; return type.flags & 32768 /* TypeParameter */ && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -37366,7 +37408,7 @@ var ts; return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); } function isArrayType(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, @@ -37811,12 +37853,12 @@ var ts; } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); } return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 393216 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { @@ -38255,7 +38297,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); + return !!constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -38280,10 +38322,12 @@ var ts; // all inferences were made to top-level occurrences 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) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. @@ -38399,7 +38443,8 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 179 /* ObjectBindingPattern */) { + var parent = element.parent; + if (parent.kind === 179 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { case 71 /* Identifier */: @@ -38415,7 +38460,7 @@ var ts; } } else { - return "" + element.parent.elements.indexOf(element); + return "" + parent.elements.indexOf(element); } } function isMatchingReference(source, target) { @@ -38443,7 +38488,7 @@ var ts; } if (source.parent.parent.kind === 231 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; - return maybeId && isMatchingReference(maybeId, t.expression); + return !!maybeId && isMatchingReference(maybeId, t.expression); } } return false; @@ -38481,7 +38526,7 @@ var ts; var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -38807,9 +38852,6 @@ var ts; } return f(type) ? type : neverType; } - // Apply a mapping function to a type and return the resulting type. If the source type - // 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; @@ -39729,7 +39771,7 @@ var ts; // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container !== undefined) { + while (container.kind !== 273 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 151 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; @@ -40345,7 +40387,7 @@ var ts; if (funcHasRestParameters && indexOfParameter === (func.parameters.length - 1) && isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + return getTypeOfSymbol(ts.last(contextualSignature.parameters)); } } } @@ -40447,7 +40489,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); + var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -40501,7 +40543,7 @@ var ts; case 6 /* Prototype */: return false; default: - ts.Debug.assertNever(kind); + return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { @@ -40590,6 +40632,25 @@ var ts; return getContextualType(attribute.parent); } } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 71 /* Identifier */: + return true; + case 184 /* PropertyAccessExpression */: + case 190 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { @@ -40606,8 +40667,8 @@ var ts; continue; if (prop.kind !== 269 /* PropertyAssignment */) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -40703,8 +40764,8 @@ var ts; return undefined; } function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -41287,7 +41348,7 @@ var ts; case 71 /* Identifier */: return ts.isIntrinsicJsxName(tagName.escapedText); default: - ts.Debug.fail(); + return ts.Debug.fail(); } } function checkJsxAttribute(node, checkMode) { @@ -41501,6 +41562,7 @@ var ts; return instantiatedSignatures; } function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (reportErrors === void 0) { reportErrors = false; } if (!node.typeArguments) { return; } @@ -41523,7 +41585,7 @@ var ts; } } // JSX global fallback - return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -41639,6 +41701,7 @@ var ts; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); + // TODO: GH#18217: callReturnType should always be defined... var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { @@ -41647,7 +41710,7 @@ var ts; var attribute = _b[_a]; if (ts.isJsxAttribute(attribute) && isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { + !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 shouldBeCandidate = false; break; } @@ -41762,7 +41825,7 @@ var ts; if (!ts.length(instantiatedSignatures)) { return unknownType; } - var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -41776,7 +41839,7 @@ var ts; checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(ts.map(instantiatedSignatures, function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); + return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -42090,7 +42153,7 @@ var ts; if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } } @@ -42130,7 +42193,7 @@ var ts; } if (type.flags & 32768 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type - type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); @@ -42231,7 +42294,7 @@ var ts; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { - error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; } @@ -42489,7 +42552,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, left, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 131072 /* Union */) && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 131072 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -42646,7 +42709,7 @@ var ts; var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { - index++; + index = index + 1; } else { lastParent = parent; @@ -42689,7 +42752,7 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call var typeArguments; // Type arguments (undefined if none) - var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". @@ -42703,8 +42766,7 @@ var ts; if (node.template.kind === 201 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. - var lastSpan = ts.lastOrUndefined(node.template.templateSpans); - ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { @@ -42882,7 +42944,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -42939,7 +43001,7 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { return false; } } @@ -42991,7 +43053,7 @@ var ts; function getEffectiveCallArguments(node) { if (node.kind === 188 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; + var args_4 = [undefined]; // TODO: GH#18217 if (template.kind === 201 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -43052,6 +43114,8 @@ var ts; // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; + default: + return ts.Debug.fail(); } } else { @@ -43139,14 +43203,15 @@ var ts; // otherwise, if the member name is a computed property name it will // be either string or symbol. var element = node; - switch (element.name.kind) { + var name = element.name; + switch (name.kind) { case 71 /* Identifier */: - return getLiteralType(ts.idText(element.name)); + return getLiteralType(ts.idText(name)); case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralType(element.name.text); + return getLiteralType(name.text); case 146 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(element.name); + var nameType = checkComputedPropertyName(name); if (isTypeAssignableToKind(nameType, 1536 /* ESSymbolLike */)) { return nameType; } @@ -43188,7 +43253,7 @@ var ts; node.kind === 156 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - var propertyType = getTypeOfNode(node); + var propertyType = getTypeOfNode(node); // TODO: GH#18217 return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); @@ -43423,7 +43488,7 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); // TODO: GH#18217 while (typeArguments_1.length > typeParameters.length) { typeArguments_1.pop(); } @@ -43742,6 +43807,8 @@ var ts; case 155 /* GetAccessor */: case 156 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); } } /** @@ -43765,8 +43832,7 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); invocationErrorRecovery(apparentType, 0 /* Call */); @@ -43830,7 +43896,7 @@ var ts; return ts.length(sigs) ? sigs[0] : unknownSignature; }) || unknownSignature; } - ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } /** * Resolve a signature of a given call-like expression. @@ -43870,7 +43936,7 @@ var ts; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; - return symbol && symbol.members !== undefined; + return !!symbol && symbol.members !== undefined; } return false; } @@ -44053,7 +44119,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -44106,6 +44172,7 @@ var ts; if (node.keywordToken === 91 /* ImportKeyword */) { return checkImportMetaProperty(node); } + return ts.Debug.assertNever(node.keywordToken); } function checkNewTargetMetaProperty(node) { var container = ts.getNewTargetContainer(node); @@ -44185,9 +44252,9 @@ var ts; } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. - var parameter = ts.lastOrUndefined(signature.parameters); + var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + var contextualParameterType = getTypeOfSymbol(ts.last(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } @@ -44607,7 +44674,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 245 /* NamespaceImport */; + return !!declaration && declaration.kind === 245 /* NamespaceImport */; } } } @@ -44731,15 +44798,15 @@ var ts; if (strict && source.flags & (1 /* Any */ | 2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */)) { return false; } - return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || - (kind & 34 /* StringLike */ && isTypeAssignableTo(source, stringType)) || - (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || - (kind & 2048 /* Void */ && isTypeAssignableTo(source, voidType)) || - (kind & 16384 /* Never */ && isTypeAssignableTo(source, neverType)) || - (kind & 8192 /* Null */ && isTypeAssignableTo(source, nullType)) || - (kind & 4096 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || - (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || - (kind & 134217728 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + return !!(kind & 84 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 34 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 136 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 2048 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 16384 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 8192 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 4096 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 512 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 134217728 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { return source.flags & 131072 /* Union */ ? @@ -44747,7 +44814,7 @@ var ts; isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -44784,7 +44851,7 @@ var ts; if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 1536 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { + if (!(rightType.flags & 1 /* Any */ || isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -45150,6 +45217,8 @@ var ts; error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; + default: + return ts.Debug.fail(); } function checkSpecialAssignment(left, right) { var special = ts.getSpecialPropertyAssignmentKind(left.parent); @@ -45243,7 +45312,9 @@ var ts; } } var func = ts.getContainingFunction(node); - var functionFlags = func ? ts.getFunctionFlags(func) : 0 /* Normal */; + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); if (!(functionFlags & 1 /* Generator */)) { // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. return anyType; @@ -45262,7 +45333,7 @@ var ts; } } var isAsync = (functionFlags & 2 /* Async */) !== 0; - var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. @@ -45355,14 +45426,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768 /* TypeParameter */) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216 /* UnionOrIntersection */) { @@ -45374,19 +45437,17 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */ | 64 /* NumberLiteral */ | 1024 /* UniqueESSymbol */) || - constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 2 /* String */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + maybeTypeOfKind(constraint, 4 /* Number */) && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 512 /* ESSymbol */) && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + return !!(contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || contextualType.flags & 64 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || contextualType.flags & 128 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */); + contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */)); } return false; } @@ -45687,7 +45748,8 @@ var ts; } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), // TODO: GH#18217 + node.type, /*headMessage*/ undefined, leadingError); } } @@ -45839,20 +45901,21 @@ var ts; else { var isStatic = ts.hasModifier(member, 32 /* Static */); var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { switch (member.kind) { case 155 /* GetAccessor */: - addName(names, member.name, memberName, 1 /* Getter */); + addName(names, name, memberName, 1 /* Getter */); break; case 156 /* SetAccessor */: - addName(names, member.name, memberName, 2 /* Setter */); + addName(names, name, memberName, 2 /* Setter */); break; case 151 /* PropertyDeclaration */: - addName(names, member.name, memberName, 3 /* Property */); + addName(names, name, memberName, 3 /* Property */); break; case 153 /* MethodDeclaration */: - addName(names, member.name, memberName, 4 /* Method */); + addName(names, name, memberName, 4 /* Method */); break; } } @@ -45916,13 +45979,14 @@ var ts; var member = _a[_i]; if (member.kind === 150 /* PropertySignature */) { var memberName = void 0; - switch (member.name.kind) { + var name = member.name; + switch (name.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - memberName = member.name.text; + memberName = name.text; break; case 71 /* Identifier */: - memberName = ts.idText(member.name); + memberName = ts.idText(name); break; default: continue; @@ -46179,7 +46243,7 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -46578,7 +46642,7 @@ var ts; case 247 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: - ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); } } } @@ -46611,7 +46675,7 @@ var ts; if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 if (isTypeAny(thenFunction)) { return undefined; } @@ -46732,7 +46796,8 @@ var ts; var thenFunction = getTypeOfPropertyOfType(type, "then"); if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); + if (!diagnosticMessage) + return ts.Debug.fail(); error(errorNode, diagnosticMessage); } return undefined; @@ -46777,7 +46842,7 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); // TODO: GH#18217 var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (returnType === unknownType) { @@ -46852,19 +46917,23 @@ var ts; break; case 148 /* Parameter */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; case 151 /* PropertyDeclaration */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 153 /* MethodDeclaration */: case 155 /* GetAccessor */: case 156 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); + var methodType = getTypeOfNode(node.parent); // TODO: GH#18217 var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; + default: + return ts.Debug.fail(); } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } @@ -47199,13 +47268,6 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 231 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 147 /* TypeParameter */) { - return; - } - } var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } @@ -47283,6 +47345,7 @@ var ts; // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. var unusedImports = ts.createMap(); var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); nodeWithLocals.locals.forEach(function (local) { // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. // If it's a type parameter merged with a parameter, check if the parameter-side is used. @@ -47303,6 +47366,11 @@ var ts; addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + if (!isIdentifierThatStartsWithUnderScore(declaration.name) || !ts.isForInOrOfStatement(declaration.parent.parent)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + } else { var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); if (parameter) { @@ -47320,47 +47388,74 @@ var ts; unusedImports.forEach(function (_a) { var importClause = _a[0], unuseds = _a[1]; var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 245 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { var unused = unuseds_1[_i]; errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } } - else if (unuseds.length === 1) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); - } - else { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); - } }); unusedDestructures.forEach(function (_a) { var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; - if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 231 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 232 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } } - else if (bindingElements.length === 1) { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 213 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + } } }); } + function bindingNameText(name) { + switch (name.kind) { + case 71 /* Identifier */: + return ts.idText(name); + case 180 /* ArrayBindingPattern */: + case 179 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } function isImportedDeclaration(node) { return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */; } function importClauseFromImported(decl) { return decl.kind === 244 /* ImportClause */ ? decl : decl.kind === 245 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } - function forEachImportedDeclaration(importClause, cb) { - var defaultName = importClause.name, namedBindings = importClause.namedBindings; - return (defaultName && cb(importClause)) || - namedBindings && (namedBindings.kind === 245 /* NamespaceImport */ ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); - } function checkBlock(node) { // Grammar checking for SyntaxKind.Block if (node.kind === 212 /* Block */) { @@ -47426,6 +47521,7 @@ var ts; } return true; } + return false; }); } function checkIfNewTargetIsCapturedInEnclosingScope(node) { @@ -47440,6 +47536,7 @@ var ts; } return true; } + return false; }); } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -47640,7 +47737,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); @@ -47885,7 +47982,7 @@ var ts; } // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (rightType === neverType || !isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { + if (rightType === neverType || !(rightType.flags & 1 /* Any */ || isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */))) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -47918,7 +48015,7 @@ var ts; */ function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { if (inputType === neverType) { - reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 return undefined; } var uplevelIteration = languageVersion >= 2 /* ES2015 */; @@ -48068,11 +48165,11 @@ var ts; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); if (isTypeAny(methodType)) { return undefined; } - var signatures = methodType && getSignaturesOfType(methodType, 0 /* Call */); + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; if (!ts.some(signatures)) { if (errorNode) { // only report on the first error @@ -48205,7 +48302,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { // Grammar checking @@ -48330,6 +48427,7 @@ var ts; grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } + return false; }); } // ensure that label is unique @@ -48389,8 +48487,8 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; // Only process instance properties with computed names here. @@ -48414,7 +48512,7 @@ var ts; errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { @@ -48509,8 +48607,8 @@ var ts; if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { // Report an error on every conflicting declaration. var name = symbolToString(symbol); - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -48519,8 +48617,8 @@ var ts; function areTypeParametersIdentical(declarations, targetParameters) { var maxTypeArgumentCount = ts.length(targetParameters); var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; // If this declaration has too few or too many type parameters, we report an error var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); var numTypeParameters = sourceParameters.length; @@ -48741,7 +48839,7 @@ var ts; if (base.flags & 4194304 /* Prototype */) { continue; } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { @@ -48770,7 +48868,7 @@ var ts; // either base or derived property is private - not override, skip it continue; } - if (isPrototypeProperty(base) && isPrototypeProperty(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; } @@ -49015,7 +49113,11 @@ var ts; case 190 /* ParenthesizedExpression */: return evaluate(expr.expression); case 71 /* Identifier */: - return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); case 185 /* ElementAccessExpression */: case 184 /* PropertyAccessExpression */: var ex = expr; @@ -49115,8 +49217,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if ((declaration.kind === 234 /* ClassDeclaration */ || (declaration.kind === 233 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304 /* Ambient */)) { @@ -49169,7 +49271,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 && !inAmbientContext - && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -49300,7 +49402,7 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (ts.nodeIsMissing(moduleName)) { + if (!moduleName || ts.nodeIsMissing(moduleName)) { // Should be a parse error. return false; } @@ -49558,8 +49660,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -49582,11 +49684,11 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var tags = _a[_i].tags; - ts.forEach(tags, checkSourceElement); - } + if (ts.isInJavaScriptFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); } var kind = node.kind; if (cancellationToken) { @@ -49759,7 +49861,7 @@ var ts; if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } - var paramTag = parent.parent; + var paramTag = node.parent.parent; if (!ts.isJSDocParameterTag(paramTag)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); return; @@ -49777,8 +49879,8 @@ var ts; function getTypeFromJSDocVariadicType(node) { var type = getTypeFromTypeNode(node.type); var parent = node.parent; - var paramTag = parent.parent; - if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); if (host_1) { @@ -49817,8 +49919,8 @@ var ts; } } function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; + for (var _i = 0, _a = deferredNodes; _i < _a.length; _i++) { + var node = _a[_i]; switch (node.kind) { case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: @@ -49845,9 +49947,9 @@ var ts; function unusedIsError(kind) { switch (kind) { case 0 /* Local */: - return compilerOptions.noUnusedLocals; + return !!compilerOptions.noUnusedLocals; case 1 /* Parameter */: - return compilerOptions.noUnusedParameters; + return !!compilerOptions.noUnusedParameters; default: return ts.Debug.assertNever(kind); } @@ -50041,22 +50143,22 @@ var ts; case 236 /* TypeAliasDeclaration */: case 237 /* EnumDeclaration */: return true; + default: + return false; } } // True if the given identifier is part of a type reference - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 145 /* QualifiedName */) { + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 145 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 161 /* TypeReference */; + return node.parent.kind === 161 /* TypeReference */; } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 184 /* PropertyAccessExpression */) { + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 184 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */; + return node.parent.kind === 206 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -50088,10 +50190,10 @@ var ts; nodeOnRightSide = nodeOnRightSide.parent; } if (nodeOnRightSide.parent.kind === 242 /* ImportEqualsDeclaration */) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } if (nodeOnRightSide.parent.kind === 248 /* ExportAssignment */) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; } @@ -50229,25 +50331,27 @@ var ts; if (node.kind === 273 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } + var parent = node.parent; + var grandParent = parent.parent; if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(node.parent); + return getSymbolOfNode(parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); + return getSymbolOfNode(parent.parent); } if (node.kind === 71 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 181 /* BindingElement */ && - node.parent.parent.kind === 179 /* ObjectBindingPattern */ && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); + else if (parent.kind === 181 /* BindingElement */ && + grandParent.kind === 179 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; @@ -50297,10 +50401,10 @@ var ts; // falls through case 8 /* NumericLiteral */: // index access - var objectType = ts.isElementAccessExpression(node.parent) - ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined - : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) - ? getTypeFromTypeNode(node.parent.parent.objectType) + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79 /* DefaultKeyword */: @@ -50405,14 +50509,14 @@ var ts; // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { if (expr.parent.kind === 269 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern ts.Debug.assert(expr.parent.kind === 182 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); // TODO: GH#18217 } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -50483,9 +50587,9 @@ var ts; return target; } // Emitter support - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var isPropertyName_1 = node.parent.kind === 184 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; @@ -50518,13 +50622,12 @@ var ts; } } function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum // declaration, we need to start resolution at the declaration's container. @@ -50558,8 +50661,8 @@ var ts; } // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value @@ -50614,9 +50717,9 @@ var ts; // When resolved as an expression identifier, if the given node references a nested block scoped entity with // a name that either hides an existing name or might hide it when compiled downlevel, // return the declaration of that entity. Otherwise, return undefined. - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { @@ -50628,8 +50731,8 @@ var ts; } // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); if (node) { var symbol = getSymbolOfNode(node); if (symbol) { @@ -50648,7 +50751,7 @@ var ts; return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 249 /* ExportDeclaration */: var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); case 248 /* ExportAssignment */: return node.expression && node.expression.kind === 71 /* Identifier */ @@ -50657,8 +50760,8 @@ var ts; } return false; } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); if (node === undefined || node.parent.kind !== 273 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; @@ -50673,11 +50776,11 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return target.flags & 67216319 /* Value */ && + return !!(target.flags & 67216319 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { if (ts.isAliasSymbolDeclaration(node)) { @@ -50685,14 +50788,14 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } - var target = getSymbolLinks(symbol).target; + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } } if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); } return false; } @@ -50719,10 +50822,10 @@ var ts; return false; } function isRequiredInitializedParameter(parameter) { - return strictNullChecks && + return !!strictNullChecks && !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && - parameter.initializer && + !!parameter.initializer && !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { @@ -50732,7 +50835,7 @@ var ts; ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + return getNodeLinks(node).flags || 0; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -50761,11 +50864,11 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 65536 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 65536 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } - function getTypeReferenceSerializationKind(typeName, location) { + function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. - typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); if (!typeName) return ts.TypeReferenceSerializationKind.Unknown; if (location) { @@ -50789,7 +50892,7 @@ var ts; } // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -50826,8 +50929,8 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { - declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { return ts.createToken(119 /* AnyKeyword */); } @@ -50845,16 +50948,16 @@ var ts; } return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { - signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { return ts.createToken(119 /* AnyKeyword */); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { - expr = ts.getParseTreeNode(expr, ts.isExpression); + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { return ts.createToken(119 /* AnyKeyword */); } @@ -50880,9 +50983,9 @@ var ts; } return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); if (reference) { var symbol = getReferencedValueSymbol(reference); if (symbol) { @@ -50940,7 +51043,7 @@ var ts; }, getNodeCheckFlags: function (node) { node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; + return node ? getNodeCheckFlags(node) : 0; }, isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, @@ -50953,8 +51056,8 @@ var ts; createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, collectLinkedAliases: collectLinkedAliases, @@ -50967,14 +51070,14 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - isLateBound: function (node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { - accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; @@ -51069,7 +51172,7 @@ var ts; } function getExternalModuleFileFromDeclaration(declaration) { var specifier = declaration.kind === 238 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } @@ -51104,7 +51207,7 @@ var ts; }); } } - // We do global augmentations seperately from module augmentations (and before creating global types) because they + // We do global augmentations separately from module augmentations (and before creating global types) because they // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require // checking for an export or property on the module (if export=) which, in turn, can fall back to the @@ -51199,7 +51302,7 @@ var ts; case 16384 /* AsyncValues */: return "__asyncValues"; case 32768 /* ExportStar */: return "__exportStar"; case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; - default: ts.Debug.fail("Unrecognized helper"); + default: return ts.Debug.fail("Unrecognized helper"); } } function resolveHelpersModule(node, errorNode) { @@ -51407,7 +51510,7 @@ var ts; return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); @@ -51415,7 +51518,7 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); } - return; + return false; } else if ((node.kind === 243 /* ImportDeclaration */ || node.kind === 242 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); @@ -51429,6 +51532,7 @@ var ts; if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } + return false; } /** * true | false: Early return this value from checkGrammarModifiers. @@ -51499,6 +51603,7 @@ var ts; if (list && list.hasTrailingComma) { return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); } + return false; } function checkGrammarTypeParameterList(typeParameters, file) { if (typeParameters && typeParameters.length === 0) { @@ -51506,6 +51611,7 @@ var ts; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); } + return false; } function checkGrammarParameterList(parameters) { var seenOptionalParameter = false; @@ -51597,6 +51703,7 @@ var ts; if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } + return false; } function checkGrammarIndexSignature(node) { // Prevent cascading error by short-circuit @@ -51609,6 +51716,7 @@ var ts; var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); } + return false; } function checkGrammarTypeArguments(node, typeArguments) { return checkGrammarForDisallowedTrailingComma(typeArguments) || @@ -51623,6 +51731,7 @@ var ts; } } } + return false; } function checkGrammarArguments(args) { return checkGrammarForOmittedArgument(args); @@ -51636,7 +51745,7 @@ var ts; var listType = ts.tokenToString(node.token); return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } - return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + return ts.some(types, checkGrammarExpressionWithTypeArguments); } function checkGrammarExpressionWithTypeArguments(node) { return checkGrammarTypeArguments(node, node.typeArguments); @@ -51701,6 +51810,7 @@ var ts; if (computedPropertyName.expression.kind === 199 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } + return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { @@ -51716,9 +51826,7 @@ var ts; } } function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } + return !!questionToken && grammarErrorOnNode(questionToken, message); } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; @@ -51746,7 +51854,7 @@ var ts; } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 153 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); @@ -51781,7 +51889,7 @@ var ts; currentKind = 4 /* SetAccessor */; break; default: - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -51914,6 +52022,7 @@ var ts; } } } + return false; } /** Does the accessor have the right number of parameters? * A get accessor has no parameters or a single `this` parameter. @@ -52140,6 +52249,7 @@ var ts; } } } + return false; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 71 /* Identifier */) { @@ -52156,6 +52266,7 @@ var ts; } } } + return false; } function checkGrammarVariableDeclarationList(declarationList) { var declarations = declarationList.declarations; @@ -52165,6 +52276,7 @@ var ts; if (!declarationList.declarations.length) { return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } + return false; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { @@ -52216,6 +52328,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); @@ -52223,6 +52336,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorOnNode(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -52230,6 +52344,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; } + return false; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); @@ -52308,6 +52423,7 @@ var ts; } } } + return false; } function checkGrammarSourceFile(node) { return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); @@ -52341,6 +52457,7 @@ var ts; // Debug.assert(isStatement(node.parent)); } } + return false; } function checkGrammarNumericLiteral(node) { // Grammar checking @@ -52361,6 +52478,7 @@ var ts; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } + return false; } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -52369,6 +52487,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } + return false; } function getAmbientModules() { if (!ambientModulesCache) { @@ -52398,6 +52517,7 @@ var ts; if (ts.isSpreadElement(nodeArguments[0])) { return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); } + return false; } } ts.createTypeChecker = createTypeChecker; @@ -52482,7 +52602,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). if (node === undefined) { - return undefined; + return node; } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; @@ -52587,7 +52707,6 @@ var ts; return name; } ts.createUniqueName = createUniqueName; - /** Create a unique name based on the supplied text. */ function createOptimisticUniqueName(text) { var name = createIdentifier(text); name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; @@ -53290,7 +53409,7 @@ var ts; function createPropertyAccess(expression, name) { var node = createSynthesizedNode(184 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); - node.name = asName(name); + node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); return node; } @@ -54013,6 +54132,7 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0 /* None */; } var node = createSynthesizedNode(232 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); @@ -54134,6 +54254,7 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0 /* None */; } var node = createSynthesizedNode(238 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); @@ -54564,7 +54685,7 @@ var ts; ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { var node = createSynthesizedNode(271 /* SpreadAssignment */); - node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } ts.createSpreadAssignment = createSpreadAssignment; @@ -54635,6 +54756,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -54861,6 +54984,7 @@ var ts; return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); } ts.createExternalModuleExport = createExternalModuleExport; + // Utilities function asName(name) { return ts.isString(name) ? createIdentifier(name) : name; } @@ -55391,7 +55515,7 @@ var ts; // Utilities function createForOfBindingStatement(node, boundValue) { if (ts.isVariableDeclarationList(node)) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); + var firstDeclaration = ts.first(node.declarations); var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, /*typeNode*/ undefined, boundValue); return ts.setTextRange(ts.createVariableStatement( @@ -55448,6 +55572,7 @@ var ts; } } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } var callee = skipOuterExpressions(expression, 7 /* All */); var thisArg; var target; @@ -55539,7 +55664,7 @@ var ts; switch (property.kind) { case 155 /* GetAccessor */: case 156 /* SetAccessor */: - return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); case 269 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); case 270 /* ShorthandPropertyAssignment */: @@ -55558,7 +55683,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, - /*type*/ undefined, getAccessor.body); + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); @@ -55569,7 +55695,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, - /*type*/ undefined, setAccessor.body); + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); @@ -55600,7 +55727,8 @@ var ts; return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, - /*type*/ undefined, method.body), + /*type*/ undefined, method.body // TODO: GH#18217 + ), /*location*/ method), /*original*/ method)), /*location*/ method), @@ -55683,6 +55811,7 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { var name = ts.getMutableClone(nodeName); @@ -55726,7 +55855,7 @@ var ts; function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); ts.setTextRange(qualifiedName, name); - var emitFlags; + var emitFlags = 0; if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -55741,7 +55870,8 @@ var ts; } ts.convertToFunctionBody = convertToFunctionBody; function convertFunctionDeclarationToExpression(node) { - ts.Debug.assert(!!node.body); + if (!node.body) + return ts.Debug.fail(); var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); @@ -55801,15 +55931,9 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - /** - * Add just the custom prologue-directives into target statement-array. - * The function needs to be called during each transformation step. - * This function needs to be called whenever we transform the statement - * list of a source file, namespace, or function-like body. - */ function addCustomPrologue(target, source, statementOffset, visitor) { var numStatements = source.length; - while (statementOffset < numStatements) { + while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); @@ -56383,7 +56507,7 @@ var ts; * Otherwise, a new StringLiteral node representing the module name will be returned. */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { - var moduleName = ts.getExternalModuleName(importNode); + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 if (moduleName.kind === 9 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) @@ -56441,8 +56565,9 @@ var ts; // `1` in `({ a: b = 1 } = ...)` // `1` in `({ a: {b} = 1 } = ...)` // `1` in `({ a: [b] = 1 } = ...)` - return ts.isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true) - ? bindingElement.initializer.right + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right : undefined; } if (ts.isShorthandPropertyAssignment(bindingElement)) { @@ -57522,7 +57647,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -57680,7 +57805,7 @@ var ts; return ts.some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { - return e.propertyName && e.propertyName.escapedText === "default" /* Default */; + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; } function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; @@ -57715,7 +57840,7 @@ var ts; ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) - return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -57942,7 +58067,7 @@ var ts; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: true, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -58003,7 +58128,7 @@ var ts; } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; function bindingOrAssignmentElementAssignsToName(element, escapedName) { - var target = ts.getTargetOfBindingOrAssignmentElement(element); + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isBindingOrAssignmentPattern(target)) { return bindingOrAssignmentPatternAssignsToName(target, escapedName); } @@ -58034,13 +58159,14 @@ var ts; * @param level Indicates the extent to which flattening should occur. */ function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } var pendingExpressions; var pendingDeclarations = []; var declarations = []; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: hoistTempVariables, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -58068,7 +58194,7 @@ var ts; } else { context.hoistVariableDeclaration(temp); - var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + var pendingDeclaration = ts.last(pendingDeclarations); pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); pendingDeclaration.value = temp; @@ -58122,7 +58248,7 @@ var ts; value = ts.createVoidZero(); } } - var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } @@ -58130,7 +58256,7 @@ var ts; flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } else { - flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 } } /** @@ -58182,7 +58308,7 @@ var ts; flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); bindingElements = undefined; } - var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); } } @@ -58956,7 +59082,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -60043,7 +60169,8 @@ var ts; * @param node The type reference node. */ function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -60069,8 +60196,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } /** @@ -60579,7 +60707,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -60628,7 +60756,7 @@ var ts; * @param node The module declaration node. */ function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -60820,7 +60948,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -61219,7 +61347,7 @@ var ts; // constructor references in static property initializers. var declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { - var classAlias = classAliases[declaration.id]; + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { var clone_1 = ts.getSynthesizedClone(classAlias); ts.setSourceMapRange(clone_1, node); @@ -61421,7 +61549,7 @@ var ts; } function visitCatchClauseInAsyncBody(node) { var catchClauseNames = ts.createUnderscoreEscapedMap(); - recordDeclarationName(node.variableDeclaration, catchClauseNames); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 // names declared in a catch variable are block scoped var catchClauseUnshadowedNames; catchClauseNames.forEach(function (_, escapedName) { @@ -61461,8 +61589,9 @@ var ts; : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } function visitForStatementInAsyncBody(node) { - return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) - ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } /** @@ -61554,10 +61683,10 @@ var ts; } } function isVariableDeclarationListWithCollidingName(node) { - return node + return !!node && ts.isVariableDeclarationList(node) && !(node.flags & 3 /* BlockScoped */) - && ts.forEach(node.declarations, collidesWithParameterName); + && node.declarations.some(collidesWithParameterName); } function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { hoistVariableDeclarationList(node); @@ -61629,7 +61758,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -62228,7 +62357,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -62256,7 +62385,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -62545,14 +62674,16 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + 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(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -63209,7 +63340,7 @@ var ts; hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 && node.kind === 224 /* ReturnStatement */ && !node.expression; } @@ -63349,7 +63480,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -63424,7 +63555,8 @@ var ts; (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; - if (!node.label) { + var label = node.label; + if (!label) { if (node.kind === 223 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; @@ -63437,12 +63569,12 @@ var ts; } else { if (node.kind === 223 /* BreakStatement */) { - labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(node.label), labelMarker); + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } else { - labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(node.label), labelMarker); + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -63603,7 +63735,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -63661,7 +63793,7 @@ var ts; // `super` call. // If this is the case, we do not include the synthetic `...args` parameter and // will instead use the `arguments` object in ES5/3. - return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } /** @@ -63697,7 +63829,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -63716,7 +63848,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -64163,7 +64295,7 @@ var ts; // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); - ts.setSourceMapRange(target, firstAccessor.name); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); ts.setSourceMapRange(propertyName, firstAccessor.name); @@ -64359,7 +64491,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { @@ -64497,13 +64629,12 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 /* ContainsBindingPattern */ - && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); if (firstDeclaration) { - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); } } return declarationList; @@ -64657,11 +64788,12 @@ var ts; } function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { var statements = []; - if (ts.isVariableDeclarationList(node.initializer)) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { if (node.initializer.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - var firstOriginalDeclaration = ts.firstOrUndefined(node.initializer.declarations); + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { // This works whether the declaration is a var, let, or const. // It will use rhsIterationValue _a[_i] as the initializer. @@ -64670,9 +64802,7 @@ var ts; ts.setOriginalNode(declarationList, node.initializer); // Adjust the source map range for the first declaration to align with the old // emitter. - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); statements.push(ts.createVariableStatement( /*modifiers*/ undefined, declarationList)); } @@ -64683,20 +64813,20 @@ var ts; /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), /*type*/ undefined, boundValue) - ]), ts.moveRangePos(node.initializer, -1)), node.initializer)), ts.moveRangeEnd(node.initializer, -1))); + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); } } else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. - var assignment = ts.createAssignment(node.initializer, boundValue); + var assignment = ts.createAssignment(initializer, boundValue); if (ts.isDestructuringAssignment(assignment)) { ts.aggregateTransformFlags(assignment); statements.push(ts.createStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); } else { - assignment.end = node.initializer.end; - statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); } } if (convertedLoopBodyStatements) { @@ -64940,7 +65070,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -65178,7 +65308,7 @@ var ts; case 156 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; case 153 /* MethodDeclaration */: @@ -65340,7 +65470,7 @@ var ts; function visitArrayLiteralExpression(node) { if (node.transformFlags & 64 /* ES2015 */) { // We are here because we contain a SpreadElementExpression. - return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } return ts.visitEachChild(node, visitor, context); } @@ -65395,11 +65525,11 @@ var ts; var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); // The class statements are the statements generated by visiting the first statement with initializer of the // body (1), while all other statements are added to remainingStatements (2) - var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); - var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); // We know there is only one variable declaration here as we verified this in an // earlier call to isTypeScriptClassWrapper var variable = varStatement.declarationList.declarations[0]; @@ -65885,14 +66015,13 @@ var ts; * @param node An original source tree node. */ function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { + switch (node.parent.kind) { case 181 /* BindingElement */: case 234 /* ClassDeclaration */: case 237 /* EnumDeclaration */: case 231 /* VariableDeclaration */: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); } return false; } @@ -66123,7 +66252,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -66308,6 +66437,7 @@ var ts; case 4 /* Yield */: return "yield"; case 5 /* YieldStar */: return "yield*"; case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 } } function transformGenerators(context) { @@ -66615,7 +66745,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -66671,13 +66801,14 @@ var ts; * @param node The node to visit. */ function visitBinaryExpression(node) { - switch (ts.getExpressionAssociativity(node)) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { case 0 /* Left */: return visitLeftAssociativeBinaryExpression(node); case 1 /* Right */: return visitRightAssociativeBinaryExpression(node); default: - ts.Debug.fail("Unknown associativity."); + return ts.Debug.assertNever(assoc); } } function isCompoundAssignment(kind) { @@ -67685,7 +67816,7 @@ var ts; beginExceptionBlock(); transformAndEmitEmbeddedStatement(node.tryBlock); if (node.catchClause) { - beginCatchBlock(node.catchClause.variableDeclaration); + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 transformAndEmitEmbeddedStatement(node.catchClause.block); } if (node.finallyBlock) { @@ -67699,7 +67830,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -67800,7 +67931,8 @@ var ts; */ function endBlock() { var block = peekBlock(); - ts.Debug.assert(block !== undefined, "beginBlock was never called."); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); var index = blockActions.length; blockActions[index] = 1 /* Close */; blockOffsets[index] = operations ? operations.length : 0; @@ -68133,7 +68265,7 @@ var ts; * @param label A label. */ function createLabel(label) { - if (label > 0) { + if (label !== undefined && label > 0) { if (labelExpressions === undefined) { labelExpressions = []; } @@ -68851,7 +68983,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -69045,7 +69177,7 @@ var ts; if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { return undefined; } - var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 var expr = getHelperExpressionForImport(node, name); if (expr === name) { return undefined; @@ -69074,7 +69206,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -70343,8 +70475,8 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependRange(statements, endLexicalEnvironment()); - var exportStarFunction = addExportStarIfNeeded(statements); + ts.prependStatements(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), ts.createPropertyAssignment("execute", ts.createFunctionExpression( @@ -70480,7 +70612,7 @@ var ts; var statements = []; for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { case 243 /* ImportDeclaration */: if (!entry.importClause) { @@ -70566,7 +70698,7 @@ var ts; function visitImportDeclaration(node) { var statements; if (node.importClause) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -70586,7 +70718,7 @@ var ts; function visitImportEqualsDeclaration(node) { ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); var statements; - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); @@ -71087,7 +71219,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -71131,9 +71263,6 @@ var ts; * @param node The node to visit. */ function visitForInitializer(node) { - if (!node) { - return node; - } if (shouldHoistForInitializer(node)) { var expressions = void 0; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { @@ -71817,7 +71946,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 231 /* VariableDeclaration */ || node.kind === 181 /* BindingElement */) { @@ -71952,7 +72081,7 @@ var ts; ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; break; default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); } return { diagnosticMessage: diagnosticMessage, @@ -72021,7 +72150,7 @@ var ts; ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; default: - ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); } } function getTypeParameterConstraintVisibilityError() { @@ -72059,7 +72188,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } return { diagnosticMessage: diagnosticMessage, @@ -72231,7 +72360,7 @@ var ts; var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) - return; // Omit declaration files from bundle results, too + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -72463,7 +72592,7 @@ var ts; } if (ts.isBindingPattern(elem.name)) { // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible - return ts.forEach(elem.name.elements, getBindingNameVisible); + return ts.some(elem.name.elements, getBindingNameVisible); } else { return resolver.isDeclarationVisible(elem); @@ -72471,11 +72600,11 @@ var ts; } function updateParamsList(node, params, modifierMask) { if (ts.hasModifier(node, 8 /* Private */)) { - return undefined; + return undefined; // TODO: GH#18217 } var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); if (!newParams) { - return undefined; + return undefined; // TODO: GH#18217 } return ts.createNodeArray(newParams, params.hasTrailingComma); } @@ -72505,7 +72634,7 @@ var ts; } function rewriteModuleSpecifier(parent, input) { if (!input) - return; + return undefined; // TODO: GH#18217 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 238 /* ModuleDeclaration */ && parent.kind !== 178 /* ImportType */); if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -72674,7 +72803,9 @@ var ts; case 154 /* Constructor */: { var isPrivate = ts.hasModifier(input, 8 /* Private */); // A constructor declaration may not have a type annotation - var ctor = ts.createSignatureDeclaration(154 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + var ctor = ts.createSignatureDeclaration(154 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), /*type*/ undefined); ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); return cleanup(ctor); @@ -72874,7 +73005,7 @@ var ts; needsDeclare = false; ts.visitNode(inner, visitDeclarationStatements); // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) - var id = "" + ts.getOriginalNodeId(inner); + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); return cleanup(ts.updateModuleDeclaration(input, @@ -72924,7 +73055,7 @@ var ts; var extendsClause_1 = ts.getClassExtendsHeritageClauseElement(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression - var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -72943,7 +73074,7 @@ var ts; return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); })); return [statement, cleanup(ts.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); @@ -73731,7 +73862,7 @@ var ts; } if (node) { var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.sourceMapRange; var _a = range || node, pos = _a.pos, end = _a.end; var source = range && range.source; @@ -73779,7 +73910,7 @@ var ts; return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { @@ -73826,7 +73957,7 @@ var ts; */ function getText() { if (disabled) { - return; + return undefined; // TODO: GH#18217 } encodeLastRecordedSourceMapSpan(); return JSON.stringify({ @@ -73844,7 +73975,7 @@ var ts; */ function getSourceMappingURL() { if (disabled) { - return; + return undefined; // TODO: GH#18217 } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url @@ -73905,7 +74036,7 @@ var ts; var currentLineMap; var detachedCommentsInfo; var hasWrittenComment = false; - var disabled = printerOptions.removeComments; + var disabled = !!printerOptions.removeComments; return { reset: reset, setWriter: setWriter, @@ -73923,7 +74054,7 @@ var ts; if (node) { hasWrittenComment = false; var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. @@ -74211,11 +74342,11 @@ var ts; detachedCommentsInfo = undefined; } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { // get the leading comments from detachedPos - var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -74270,6 +74401,7 @@ var ts; * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. */ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { @@ -74300,7 +74432,7 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { @@ -74371,7 +74503,7 @@ var ts; emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, - sourceMaps: sourceMapDataList + sourceMaps: sourceMapDataList, }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -74478,7 +74610,7 @@ var ts; ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); // Write bundled offset information if applicable if (bundleInfoPath) { bundleInfo.totalLength = writer.getTextPos(); @@ -74662,7 +74794,7 @@ var ts; } } function setWriter(output) { - writer = output; + writer = output; // TODO: GH#18217 comments.setWriter(output); } function reset() { @@ -74720,8 +74852,7 @@ var ts; return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode); - onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); + ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); } function pipelineEmitWithComments(hint, node) { ts.Debug.assertDefined(emitNodeWithComments); @@ -74733,9 +74864,8 @@ var ts; pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assertDefined(onEmitSourceMapOfNode); ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */); - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); + ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { if (hint === 0 /* SourceFile */) @@ -75988,7 +76118,7 @@ var ts; writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emitIdentifierName(node.name); + emitIdentifierName(node.name); // TODO: GH#18217 emitSignatureAndBody(node, emitSignatureHead); } function emitBlockCallback(_hint, body) { @@ -76357,7 +76487,7 @@ var ts; } function emitJsxAttribute(node) { emit(node.name); - emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); @@ -76491,7 +76621,7 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) @@ -76719,7 +76849,7 @@ var ts; emitNodeList(emit, parentNode, children, format, start, count); } function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { switch (format & 28 /* DelimitersMask */) { @@ -76745,7 +76875,7 @@ var ts; if (isUndefined && format & 8192 /* OptionalIfUndefined */) { return; } - var isEmpty = isUndefined || start >= children.length || count === 0; + var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 16384 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -76758,6 +76888,7 @@ var ts; if (format & 7680 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -76777,7 +76908,7 @@ var ts; // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; - if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } @@ -76790,7 +76921,7 @@ var ts; } // Emit each child. var previousSibling = void 0; - var shouldDecreaseIndentAfterEmit = void 0; + var shouldDecreaseIndentAfterEmit = false; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -76868,6 +76999,7 @@ var ts; } if (format & 7680 /* BracketsMask */) { if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -77396,7 +77528,7 @@ var ts; * Generates a unique name for an ImportDeclaration or ExportDeclaration. */ function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 var baseName = ts.isStringLiteral(expr) ? ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); @@ -77458,7 +77590,7 @@ var ts; case 3 /* Unique */: return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); } - ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } /** * Gets the node from which a name should be generated. @@ -77921,8 +78053,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); - var mtimeBefore = ts.sys.getModifiedTime(fileName); + var hash = ts.sys.createHash(data); // TODO: GH#18217 + var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -77934,7 +78066,7 @@ var ts; } } ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); + var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -78005,7 +78137,7 @@ var ts; function formatDiagnostic(diagnostic, host) { 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 _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 var fileName = diagnostic.file.fileName; var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; @@ -78052,7 +78184,7 @@ var ts; var context_2 = ""; if (diagnostic.file) { var start = diagnostic.start, length_4 = diagnostic.length, file_9 = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; + var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 var _b = ts.getLineAndCharacterOfPosition(file_9, start + length_4), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file_9, file_9.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file_9.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_9.fileName; @@ -78196,8 +78328,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -78228,9 +78359,9 @@ var ts; }; } function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { - var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; - var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; + var oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -78257,7 +78388,7 @@ var ts; // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); - host = host || createCompilerHost(options); + var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); @@ -78285,7 +78416,7 @@ var ts; } else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -78293,7 +78424,7 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -78427,7 +78558,7 @@ var ts; } else if (options.composite) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -78548,7 +78679,7 @@ var ts; // `result[i]` is either a `ResolvedModuleFull` or a marker. // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + result[i] = undefined; // TODO: GH#18217 } } else { @@ -78561,7 +78692,7 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same @@ -78657,7 +78788,7 @@ var ts; var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; } @@ -78843,7 +78974,7 @@ var ts; return nodes; } function isSourceFileFromExternalLibrary(file) { - return sourceFilesFoundSearchingNodeModules.get(file.path); + return !!sourceFilesFoundSearchingNodeModules.get(file.path); } function isSourceFileDefaultLibrary(file) { if (file.hasNoDefaultLib) { @@ -78859,7 +78990,7 @@ var ts; return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } } function getDiagnosticsProducingTypeChecker() { @@ -78912,7 +79043,8 @@ var ts; var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -79003,11 +79135,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } /** @@ -79017,7 +79157,7 @@ var ts; var file = diagnostic.file, start = diagnostic.start; if (file) { var lineStarts = ts.getLineStarts(file); - var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 while (line > 0) { var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); @@ -79224,7 +79364,7 @@ var ts; if (cachedResult) { return cachedResult; } - var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 if (sourceFile) { if (!cache.perFile) { cache.perFile = ts.createMap(); @@ -79404,7 +79544,8 @@ var ts; } /** This has side effects through `findSourceFile`. */ function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -79496,7 +79637,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 redirectTargetsSet.set(fileFromPackageId.path, true); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -79591,7 +79732,7 @@ var ts; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 } else { // If we already resolved to this file, it must have been a secondary reference. Check file contents @@ -79601,7 +79742,8 @@ var ts; if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } } // don't overwrite previous resolution result @@ -79614,7 +79756,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 } if (saveResolution) { resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); @@ -79718,7 +79860,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(host, ref); // TODO: GH#18217 // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -79729,13 +79871,13 @@ var ts; return { commandLine: commandLine, sourceFile: sourceFile }; } function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); } function getDeclarationOutputDirectory(proj) { return proj.options.declarationDir || proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); + ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !options.strictNullChecks) { @@ -79990,9 +80132,9 @@ var ts; if (ts.isObjectLiteralExpression(pathProp.initializer)) { for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { var keyProps = _b[_a]; - if (ts.isArrayLiteralExpression(keyProps.initializer) && - keyProps.initializer.elements.length > valueIndex) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); needCompilerDiagnostic = false; } } @@ -80053,7 +80195,7 @@ var ts; if (_referencesArrayLiteralSyntax === undefined) { _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword if (options.configFile) { - var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { var prop = _a[_i]; if (ts.isArrayLiteralExpression(prop.initializer)) { @@ -80095,6 +80237,7 @@ var ts; return false; } programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + return false; // TODO: GH#18217 This function always returns `false`!` } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); @@ -80114,6 +80257,10 @@ var ts; if (out) { return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } // If --outDir, check if file is in that directory if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); @@ -80121,8 +80268,8 @@ var ts; if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); - return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts" /* Ts */)) || - !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx" /* Tsx */)); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); } return false; } @@ -80247,7 +80394,7 @@ var ts; if (!resolvedTypeReferenceDirective) { return; } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); @@ -80279,7 +80426,7 @@ var ts; for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var version_1 = sourceFile.version; - var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -80342,7 +80489,8 @@ var ts; return false; } var info = state.fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); + if (!info) + return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { @@ -80354,7 +80502,7 @@ var ts; latestSignature = computeHash(emitOutput.outputFiles[0].text); } else { - latestSignature = prevSignature; + latestSignature = prevSignature; // TODO: GH#18217 } } cacheToUpdateSignature.set(sourceFile.path, latestSignature); @@ -80489,8 +80637,9 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { - queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); } } } @@ -80505,7 +80654,7 @@ var ts; (function (ts) { function hasSameKeys(map1, map2) { // Has same size and every key is present in both maps - return map1 === map2 || map1 && map2 && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); } /** * Create the state so that we can iterate on changedFiles/affected files @@ -80533,7 +80682,7 @@ var ts; } // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; - var oldReferencedMap = useOldState && oldState.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -80577,7 +80726,7 @@ var ts; var affectedFiles = state.affectedFiles; if (affectedFiles) { var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; - var affectedFilesIndex = state.affectedFilesIndex; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 while (affectedFilesIndex < affectedFiles.length) { var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.path)) { @@ -80690,7 +80839,7 @@ var ts; // Return same program if underlying program doesnt change var oldState = oldProgram && oldProgram.getState(); if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { - newProgram = undefined; + newProgram = undefined; // TODO: GH#18217 oldState = undefined; return oldProgram; } @@ -80704,7 +80853,7 @@ var ts; var computeHash = host.createHash || ts.identity; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); // To ensure that we arent storing any references to old program or new program without state - newProgram = undefined; + newProgram = undefined; // TODO: GH#18217 oldProgram = undefined; oldState = undefined; var result = { @@ -80765,7 +80914,7 @@ var ts; if (!targetSourceFile) { // Emit and report any errors we ran into. var sourceMaps = []; - var emitSkipped = void 0; + var emitSkipped = false; var diagnostics = void 0; var emittedFiles = []; var affectedEmitResult = void 0; @@ -80885,7 +81034,7 @@ var ts; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; - var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. // The key in the map is source file's path. @@ -80906,7 +81055,7 @@ var ts; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); - var rootPath = rootDir && resolutionHost.toPath(rootDir); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames var typeRootsWatches = ts.createMap(); return { @@ -80964,7 +81113,7 @@ var ts; } // Invalidated if file has unresolved imports var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); - return value && !!value.length; + return !!value && !!value.length; } function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { @@ -80974,7 +81123,7 @@ var ts; } var collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = undefined; - return function (path) { return (collected && collected.has(path)) || + return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { @@ -81055,7 +81204,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -81126,7 +81275,7 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - return { dir: rootDir, dirPath: rootPath }; + return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } @@ -81190,7 +81339,7 @@ var ts; } } if (setAtRoot) { - setDirectoryWatcher(rootDir, rootPath); + setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 } } function setDirectoryWatcher(dir, dirPath, subDirectory) { @@ -81339,7 +81488,7 @@ var ts; // Resolution is invalidated if the resulting file name is same as the deleted file path function (resolution, getResolutionWithResolvedFileName) { var result = getResolutionWithResolvedFileName(resolution); - return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 }); } function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { @@ -81395,7 +81544,7 @@ var ts; return rootPath; } var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info @@ -81462,7 +81611,7 @@ var ts; getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, getNewLine: function () { return ts.sys.newLine; }, getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) - } : undefined; + } : undefined; // TODO: GH#18217 /** * Create a function that reports error by writing to the system and handles the formating of the diagnostic */ @@ -81479,7 +81628,7 @@ var ts; return function (diagnostic) { diagnostics[0] = diagnostic; system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); - diagnostics[0] = undefined; + diagnostics[0] = undefined; // TODO: GH#18217 }; } ts.createDiagnosticReporter = createDiagnosticReporter; @@ -81539,7 +81688,7 @@ var ts; var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); - host.onUnRecoverableConfigFileDiagnostic = undefined; + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; @@ -81669,9 +81818,9 @@ var ts; * Creates the watch compiler host from system for config file in watch mode */ function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { - reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); - var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; return host; @@ -81691,7 +81840,7 @@ var ts; (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -81718,7 +81867,7 @@ var ts; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; - var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } @@ -81748,7 +81897,7 @@ var ts; var trace = host.trace && (function (s) { host.trace(s + newLine); }); var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : compilerOptions.diagnostis ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); @@ -81770,7 +81919,7 @@ var ts; readFile: readFile, trace: trace, directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), realpath: host.realpath && (function (s) { return host.realpath(s); }), getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), onReleaseOldSourceFile: onReleaseOldSourceFile, @@ -82059,12 +82208,12 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; - configFileSpecs = configFileParseResult.configFileSpecs; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } @@ -82443,6 +82592,13 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, + { + name: "strictAny", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_any_type + }, { name: "strictNullChecks", type: "boolean", @@ -82948,7 +83104,7 @@ var ts; case "string": return ts.map(values, function (v) { return v || ""; }); default: - return ts.filter(ts.map(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }), function (v) { return !!v; }); + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); } } ts.parseListTypeOption = parseListTypeOption; @@ -83371,6 +83527,7 @@ var ts; var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } + return false; } /** * Generate tsconfig configuration when running command line "--init" @@ -83423,7 +83580,7 @@ var ts; } else { if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 } else { // There is a typeMap associated with this command-line option so use it to map value back to its name @@ -83850,13 +84007,10 @@ var ts; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return undefined; + return false; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; + return typeof result === "boolean" && result; } function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; @@ -83885,7 +84039,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -84282,7 +84436,7 @@ var ts; if (optionEnumValue === value) { return optionStringValue; } - }); + }); // TODO: GH#18217 } } })(ts || (ts = {})); @@ -84710,7 +84864,7 @@ var ts; ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { var target = climbPastPropertyAccess(node); - return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -84773,6 +84927,8 @@ var ts; return true; case 177 /* LiteralType */: return node.parent.parent.kind === 175 /* IndexedAccessType */; + default: + return false; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -84946,7 +85102,7 @@ var ts; } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { + if (n === undefined || ts.nodeIsMissing(n)) { return false; } switch (n.kind) { @@ -84996,7 +85152,7 @@ var ts; // having at least a closing paren. return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); case 238 /* ModuleDeclaration */: - return n.body && isCompletedNode(n.body, sourceFile); + return !!n.body && isCompletedNode(n.body, sourceFile); case 216 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); @@ -85066,11 +85222,11 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last_2 = ts.lastOrUndefined(children); - if (last_2.kind === expectedLastToken) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { return true; } - else if (last_2.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -85130,6 +85286,7 @@ var ts; ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { + if (includeEndPosition === void 0) { includeEndPosition = false; } return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, includeEndPosition, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; @@ -85344,10 +85501,11 @@ var ts; var tokenKind = token.kind; var remainingMatchingTokens = 0; while (true) { - token = findPrecedingToken(token.getFullStart(), sourceFile); - if (!token) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { return undefined; } + token = preceding; if (token.kind === matchingTokenKind) { if (remainingMatchingTokens === 0) { return token; @@ -85360,21 +85518,24 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(token, sourceFile) { + function isPossiblyTypeArgumentPosition(tokenIn, sourceFile) { + var token = tokenIn; // This function determines if the node could be type argument position // Since during editing, when type argument list is not complete, // the tree could be of any shape depending on the tokens parsed before current node, // scanning of the previous identifier followed by "<" before current node would give us better result // Note that we also balance out the already provided type arguments, arrays, object literals while doing so var remainingLessThanTokens = 0; + var nTypeArguments = 0; while (token) { switch (token.kind) { case 27 /* LessThanToken */: // Found the beginning of the generic argument expression token = findPrecedingToken(token.getFullStart(), sourceFile); - var tokenIsIdentifier = token && ts.isIdentifier(token); - if (!remainingLessThanTokens || !tokenIsIdentifier) { - return tokenIsIdentifier; + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return { called: token, nTypeArguments: nTypeArguments }; } remainingLessThanTokens--; break; @@ -85392,24 +85553,26 @@ var ts; // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); if (!token) - return false; + return undefined; break; case 20 /* CloseParenToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); if (!token) - return false; + return undefined; break; case 22 /* CloseBracketToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); if (!token) - return false; + return undefined; break; // Valid tokens in a type name. Skip. case 26 /* CommaToken */: + nTypeArguments++; + break; case 36 /* EqualsGreaterThanToken */: case 71 /* Identifier */: case 9 /* StringLiteral */: @@ -85429,11 +85592,11 @@ var ts; break; } // Invalid token in type - return false; + return undefined; } token = findPrecedingToken(token.getFullStart(), sourceFile); } - return false; + return undefined; } ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; /** @@ -85636,7 +85799,7 @@ var ts; } ts.repeatString = repeatString; function skipConstraint(type) { - return type.isTypeParameter() ? type.getConstraint() : type; + return type.isTypeParameter() ? type.getConstraint() : type; // TODO: GH#18217 } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { @@ -85662,16 +85825,16 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier) { + function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) - : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier, preferences.quotePreference === "single") : moduleSpecifier); } ts.makeImport = makeImport; function symbolNameNoDefault(symbol) { @@ -85897,18 +86060,21 @@ var ts; } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { - typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); @@ -85916,7 +86082,7 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return location.parent && + return !!location.parent && (location.parent.kind === 247 /* ImportSpecifier */ || location.parent.kind === 251 /* ExportSpecifier */) && location.parent.propertyName === location; } @@ -85944,7 +86110,7 @@ var ts; scriptKinds[_i - 2] = arguments[_i]; } var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); } ts.scriptKindIs = scriptKindIs; function getScriptKind(fileName, host) { @@ -86356,6 +86522,8 @@ var ts; case 9 /* text */: case 17 /* parameterName */: return ts.TokenClass.Identifier; + default: + return undefined; // TODO: GH#18217 Debug.assertNever(type); } } /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ @@ -86603,6 +86771,7 @@ var ts; case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; case 23 /* jsxText */: return "jsx text" /* jsxText */; case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type); } } function convertClassificationsToSpans(classifications) { @@ -86859,19 +87028,20 @@ var ts; } if (ts.isPunctuation(tokenKind)) { if (token) { + var parent = token.parent; if (tokenKind === 58 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 231 /* VariableDeclaration */ || - token.parent.kind === 151 /* PropertyDeclaration */ || - token.parent.kind === 148 /* Parameter */ || - token.parent.kind === 261 /* JsxAttribute */) { + if (parent.kind === 231 /* VariableDeclaration */ || + parent.kind === 151 /* PropertyDeclaration */ || + parent.kind === 148 /* Parameter */ || + parent.kind === 261 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 199 /* BinaryExpression */ || - token.parent.kind === 197 /* PrefixUnaryExpression */ || - token.parent.kind === 198 /* PostfixUnaryExpression */ || - token.parent.kind === 200 /* ConditionalExpression */) { + if (parent.kind === 199 /* BinaryExpression */ || + parent.kind === 197 /* PrefixUnaryExpression */ || + parent.kind === 198 /* PostfixUnaryExpression */ || + parent.kind === 200 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -86881,6 +87051,7 @@ var ts; return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { + // TODO: GH#18217 return token.parent.kind === 261 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 12 /* RegularExpressionLiteral */) { @@ -87006,7 +87177,7 @@ var ts; // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; - }); + }); // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } @@ -87210,8 +87381,8 @@ var ts; // after the last '/' that appears in the fragment because that's where the replacement span // starts if (fragmentDirectory !== undefined) { - var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); - return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); }); + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); } return nonRelativeModuleNames; } @@ -87321,7 +87492,7 @@ var ts; } return result; } - // Replace everything after the last directory seperator that appears + // Replace everything after the last directory separator that appears function getDirectoryFragmentTextSpan(text, textStart) { var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); var offset = index !== -1 ? index + 1 : 0; @@ -87366,7 +87537,7 @@ var ts; return ts.directoryProbablyExists(path, host); } catch ( /*ignore*/_a) { /*ignore*/ } - return undefined; + return false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; @@ -87414,7 +87585,7 @@ var ts; } var contextToken = ts.findPrecedingToken(position, sourceFile); if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) - return undefined; + return undefined; // TODO: GH#18217 if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined @@ -87424,7 +87595,7 @@ var ts; && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(program, log, sourceFile, position, preferences, /*detailsEntryId*/ undefined); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); if (!completionData) { return undefined; } @@ -87494,9 +87665,9 @@ var ts; }] }; } var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { + if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); + getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -87514,6 +87685,9 @@ var ts; } return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } function isMemberCompletionKind(kind) { switch (kind) { case 0 /* ObjectPropertyDeclaration */: @@ -87632,7 +87806,7 @@ var ts; continue; } // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 uniques.set(name, true); } entries.push(entry); @@ -87728,7 +87902,7 @@ var ts; case 186 /* CallExpression */: case 187 /* NewExpression */: if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); // f("/*completion position*/") @@ -87783,7 +87957,8 @@ var ts; : ts.emptyArray; } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { - var completionData = getCompletionData(program, log, sourceFile, position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); if (!completionData) { return { type: "none" }; } @@ -87797,7 +87972,7 @@ var ts; // completion entry. return ts.firstDefined(symbols, function (symbol) { var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - var info = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, origin, completionKind); + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; @@ -87819,7 +87994,7 @@ var ts; var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); - return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); @@ -87840,7 +88015,7 @@ var ts; case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; - return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. @@ -87905,12 +88080,15 @@ var ts; CompletionKind[CompletionKind["None"] = 5] = "None"; })(CompletionKind || (CompletionKind = {})); function getRecommendedCompletion(currentToken, position, sourceFile, checker) { - var ty = getContextualType(currentToken, position, sourceFile, checker); - var symbol = ty && ty.symbol; - // Don't include make a recommended completion for an abstract class - return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) - ? getFirstSymbolInChain(symbol, currentToken, checker) - : undefined; + var contextualType = getContextualType(currentToken, position, sourceFile, checker); + // For a union, return the first one with a recommended completion. + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, currentToken, checker) + : undefined; + }); } function getContextualType(currentToken, position, sourceFile, checker) { var parent = currentToken.parent; @@ -87920,7 +88098,7 @@ var ts; case 58 /* EqualsToken */: switch (parent.kind) { case 231 /* VariableDeclaration */: - return checker.getContextualType(parent.initializer); + return checker.getContextualType(parent.initializer); // TODO: GH#18217 case 199 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); case 261 /* JsxAttribute */: @@ -87935,7 +88113,7 @@ var ts; case 17 /* OpenBraceToken */: return ts.isJsxExpression(parent) && parent.parent.kind !== 254 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: - var argInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(currentToken, position, sourceFile); + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(currentToken, position, sourceFile); return argInfo // At `,`, treat this as the next argument after the comma. ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (currentToken.kind === 26 /* CommaToken */ ? 1 : 0)) @@ -87974,7 +88152,7 @@ var ts; function isModuleSymbol(symbol) { return symbol.declarations.some(function (d) { return d.kind === 273 /* SourceFile */; }); } - function getCompletionData(program, log, sourceFile, position, preferences, detailsEntryId) { + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 @@ -88046,7 +88224,7 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217 log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file @@ -88055,7 +88233,7 @@ var ts; // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { var start_4 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } // Find the node where completion is requested on. @@ -88086,6 +88264,7 @@ var ts; node = parent.left; break; case 178 /* ImportType */: + case 209 /* MetaProperty */: node = parent; break; default: @@ -88195,6 +88374,8 @@ var ts; case 294 /* JSDocTypeTag */: case 296 /* JSDocTypedefTag */: return true; + default: + return false; } } function getTypeScriptMemberSymbols() { @@ -88232,13 +88413,18 @@ var ts; } } } + if (ts.isMetaProperty(node) && (node.keywordToken === 94 /* NewKeyword */ || node.keywordToken === 91 /* ImportKeyword */)) { + var completion = (node.keywordToken === 94 /* NewKeyword */) ? "target" : "meta"; + symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); + return; + } if (!isTypeLocation) { addTypeProperties(typeChecker.getTypeAtLocation(node)); } } function addTypeProperties(type) { isNewIdentifierLocation = hasIndexSignature(type); - if (ts.isSourceFileJavaScript(sourceFile)) { + if (isUncheckedFile) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that // each individual type has. This is because we're going to add all identifiers @@ -88377,7 +88563,7 @@ var ts; if (ts.programContainsEs6Modules(program)) return true; // For JS, stay on the safe side. - if (ts.isSourceFileJavaScript(sourceFile)) + if (isUncheckedFile) return false; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); @@ -88457,6 +88643,7 @@ var ts; // symbol can be referenced at locations where type is allowed return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); } + return false; } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { var tokenTextLowerCase = tokenText.toLowerCase(); @@ -88539,7 +88726,7 @@ var ts; return true; } if (contextToken.parent.kind === 257 /* JsxClosingElement */ || contextToken.parent.kind === 255 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 254 /* JsxElement */; + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 254 /* JsxElement */; } } return false; @@ -88696,7 +88883,7 @@ var ts; // cursor is in an import clause // try to show exported member for imported module var moduleSpecifier = (namedImportsOrExports.kind === 246 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; completionKind = 3 /* MemberLike */; @@ -88723,7 +88910,7 @@ var ts; if (!ts.isClassLike(decl)) return 1 /* Success */; var classElement = contextToken.parent; - var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; // If this is context token is not something we are editing now, consider if this would lead to be modifier if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { @@ -88739,7 +88926,7 @@ var ts; if (!(classElementModifierFlags & 8 /* Private */)) { // List of property symbols of base type that are not private and already implemented var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { - var type = typeChecker.getTypeAtLocation(baseTypeNode); + var type = typeChecker.getTypeAtLocation(baseTypeNode); // TODO: GH#18217 return typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); }); symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); @@ -88774,13 +88961,14 @@ var ts; */ function tryGetConstructorLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 19 /* OpenParenToken */: case 26 /* CommaToken */: - return ts.isConstructorDeclaration(contextToken.parent) && contextToken.parent; + return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; default: if (isConstructorParameterCompletion(contextToken)) { - return contextToken.parent.parent; + return parent.parent; } } } @@ -88797,6 +88985,7 @@ var ts; return true; } prev_1 = node; + return false; }); return container && container; } @@ -88862,7 +89051,8 @@ var ts; * @returns true if we are certain that the currently edited location must define a new location; false otherwise. */ function isSolelyIdentifierDefinitionLocation(contextToken) { - var containingNodeKind = contextToken.parent.kind; + var parent = contextToken.parent; + var containingNodeKind = parent.kind; switch (contextToken.kind) { case 26 /* CommaToken */: return containingNodeKind === 231 /* VariableDeclaration */ || @@ -88875,9 +89065,9 @@ var ts; containingNodeKind === 236 /* TypeAliasDeclaration */ || // type Map, K, | // class A= contextToken.pos); + (ts.isClassLike(parent) && + !!parent.typeParameters && + parent.typeParameters.end >= contextToken.pos); case 23 /* DotToken */: return containingNodeKind === 180 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: @@ -88896,15 +89086,14 @@ var ts; containingNodeKind === 236 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 151 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); + return containingNodeKind === 151 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 148 /* Parameter */ || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 180 /* ArrayBindingPattern */); // var [...z| + (!!parent.parent && parent.parent.kind === 180 /* ArrayBindingPattern */); // var [...z| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 148 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); + return containingNodeKind === 148 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 118 /* AsKeyword */: return containingNodeKind === 247 /* ImportSpecifier */ || containingNodeKind === 251 /* ExportSpecifier */ || @@ -89005,7 +89194,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 181 /* BindingElement */ && m.propertyName) { + if (ts.isBindingElement(m) && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 71 /* Identifier */) { existingName = m.propertyName.escapedText; @@ -89018,7 +89207,7 @@ var ts; var name = ts.getNameOfDeclaration(m); existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } - existingMemberNames.set(existingName, true); + existingMemberNames.set(existingName, true); // TODO: GH#18217 } return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); } @@ -89255,7 +89444,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) + return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -89337,7 +89526,7 @@ var ts; if (!sourceFilesSet.has(fileName)) { ts.Debug.assert(program.redirectTargetsSet.has(fileName)); var redirectTarget_1 = program.getSourceFile(fileName); - var redirect = ts.find(sourceFilesToSearch, function (f) { return f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; ts.Debug.assert(sourceFilesSet.has(fileName)); } @@ -89410,7 +89599,7 @@ var ts; } else if (ts.isTryStatement(node)) { // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. - return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), aggregateOwnedThrowStatements(node.finallyBlock)); + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); } // Do not cross function boundaries. return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); @@ -89451,7 +89640,7 @@ var ts; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; + return !!actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { @@ -89502,9 +89691,8 @@ var ts; } case 154 /* Constructor */: case 153 /* MethodDeclaration */: - case 233 /* FunctionDeclaration */: { + case 233 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - } case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: var nodes = container.members; @@ -89720,6 +89908,11 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. @@ -89733,7 +89926,7 @@ var ts; if (!bucket && createIfMissing) { buckets.set(key, bucket = ts.createMap()); } - return bucket; + return bucket; // TODO: GH#18217 } function reportStats() { var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { @@ -89742,8 +89935,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -89774,13 +89966,26 @@ var ts; var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } @@ -89789,7 +89994,10 @@ var ts; // the script snapshot. If so, update it appropriately. Otherwise, we can just // return it as is. if (entry.sourceFile.version !== version) { - entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } // If we're acquiring, then this is the first time this LS is asking for this document. // Increase our ref count so we know there's another LS using the document. If we're @@ -89800,6 +90008,7 @@ var ts; entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -89817,6 +90026,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -89824,11 +90040,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -89965,7 +90182,7 @@ var ts; ts.Debug.assert(!isAvailableThroughGlobal); var isNew = markSeenIndirectUser(sourceFileLike); if (isNew) { - indirectUserDeclarations.push(sourceFileLike); + indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217 } return isNew; } @@ -90046,7 +90263,7 @@ var ts; return; } if (exportKind === 0 /* Named */) { - searchForNamedImport(namedBindings); + searchForNamedImport(namedBindings); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) } else { // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals @@ -90110,7 +90327,7 @@ var ts; /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); - return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { if (!ts.isExportDeclaration(statement)) return; var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; @@ -90216,12 +90433,13 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; + var grandParent = parent.parent; if (symbol.exportSymbol) { if (parent.kind === 184 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) - ? getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ false) + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) : undefined; } else { @@ -90248,15 +90466,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(parent.parent)) { - return getExportAssignmentExport(parent.parent); + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(parent.parent)) { - return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -90331,6 +90549,9 @@ var ts; else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } // If a reference is a class expression, the exported node would be its parent. @@ -90626,6 +90847,7 @@ var ts; } var moduleReferences = ts.emptyArray; var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; if (moduleSourceFile) { var exportEquals = symbol.exports.get("export=" /* ExportEquals */); // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. @@ -90634,13 +90856,13 @@ var ts; return moduleReferences; // Continue to get references to 'export ='. symbol = ts.skipAlias(exportEquals, checker); - node = undefined; + referencedNode = undefined; } - return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; function isModuleSymbol(symbol) { - return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile); + return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; } function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); @@ -90718,7 +90940,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -90826,7 +91048,7 @@ var ts; State.prototype.getImportSearches = function (exportSymbol, exportInfo) { if (!this.importTracker) this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); - return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); }; /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { @@ -90837,7 +91059,7 @@ var ts; // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** @@ -90938,8 +91160,9 @@ var ts; } } function getPropertySymbolOfDestructuringAssignment(location, checker) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - checker.getPropertySymbolOfDestructuringAssignment(location); + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; } function getObjectBindingElementWithoutPropertyName(symbol) { var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */); @@ -90998,8 +91221,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -91018,7 +91241,7 @@ var ts; // declare module "a" { export type T = number; } // declare module "b" { import { T } from "a"; export const x: T; } // 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; + return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 } /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ function isSymbolReferencedInFile(definition, checker, sourceFile) { @@ -91210,7 +91433,8 @@ var ts; if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - ts.Debug.assert(!!exportInfo); + if (!exportInfo) + return ts.Debug.fail(); searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. @@ -91346,8 +91570,7 @@ var ts; } /** Find references to `super` in the constructor of an extending class. */ function findSuperConstructorAccesses(cls, addNode) { - var symbol = cls.symbol; - var ctr = symbol.members.get("__constructor" /* Constructor */); + var ctr = cls.symbol.members.get("__constructor" /* Constructor */); if (!ctr) { return; } @@ -91690,7 +91913,7 @@ var ts; var name = ts.getNameFromPropertyName(node.name); var symbol = contextualType && name && contextualType.getProperty(name); return symbol ? [symbol] : - contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; + contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; // TODO: GH#18217 } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations @@ -91712,8 +91935,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -91774,6 +91997,72 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { + var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; + var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); + if (newPath !== undefined) { + var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); + changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); + } + } + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); + if (oldFile) { + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + } + } + function isRef(toUpdate) { + return "fileName" in toUpdate; + } + function getImportsToUpdate(program, oldFilePath, host) { + var result = []; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var ref = _c[_b]; + if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { + result.push({ sourceFile: sourceFile, toUpdate: ref }); + } + } + for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { + var importStringLiteral = _e[_d]; + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + // We may or may not have picked up on the file being renamed, so maybe successfully resolved to oldFilePath, or maybe that's in failedLookupLocations + if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { + result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); + } + } + } + return result; + } + function getPathUpdater(oldFilePath, newFilePath, host) { + // Get the relative path from old to new location, and append it on to the end of imports and normalize. + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + return function (oldPath) { + if (!ts.pathIsRelative(oldPath)) + return; + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + }; + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -91786,10 +92075,11 @@ var ts; if (node === sourceFile) { return undefined; } + var parent = node.parent; // Labels if (ts.isJumpStatementTarget(node)) { var label = ts.getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } var typeChecker = program.getTypeChecker(); var symbol = getSymbol(node, typeChecker); @@ -91805,7 +92095,7 @@ var ts; // If this is the original constructor definition, parent is the class. return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) || // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias - symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); }) + symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); }) ? [sigInfo] : [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node)); } @@ -91829,9 +92119,9 @@ var ts; // pr/*destination*/op1: number // } // bar(({pr/*goto*/op1})=>{}); - if (ts.isPropertyName(node) && ts.isBindingElement(node.parent) && ts.isObjectBindingPattern(node.parent.parent) && - (node === (node.parent.propertyName || node.parent.name))) { - var type = typeChecker.getTypeAtLocation(node.parent.parent); + if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var type = typeChecker.getTypeAtLocation(parent.parent); if (type) { var propSymbols = ts.getPropertySymbolsFromType(type, node); if (propSymbols) { @@ -91866,7 +92156,7 @@ var ts; var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - var file_17 = reference && program.getSourceFile(reference.resolvedFileName); + var file_17 = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 return file_17 && { fileName: typeReferenceDirective.fileName, file: file_17 }; } return undefined; @@ -92009,14 +92299,14 @@ var ts; kind: "script" /* scriptElement */, name: name, containerName: undefined, - containerKind: undefined + containerKind: undefined, }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ function getAncestorCallLikeExpression(node) { var target = climbPastManyPropertyAccesses(node); var callLike = target.parent; - return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; } function climbPastManyPropertyAccesses(node) { return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; @@ -92220,7 +92510,7 @@ var ts; if (!ts.isIdentifier(param.name)) return undefined; var name = param.name.text; - if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217 || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { return undefined; } @@ -92378,7 +92668,7 @@ var ts; return rightHandSide.parameters; case 204 /* ClassExpression */: { var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); - return ctr && ctr.parameters; + return ctr ? ctr.parameters : ts.emptyArray; } } return ts.emptyArray; @@ -92589,7 +92879,7 @@ var ts; return result; function addInferredTyping(typingName) { if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); + inferredTypings.set(typingName, undefined); // TODO: GH#18217 } } function addInferredTypings(typingNames, message) { @@ -92740,7 +93030,7 @@ var ts; case 0 /* Ok */: return ts.Debug.fail(); // Shouldn't have called this. default: - ts.Debug.assertNever(result); + throw ts.Debug.assertNever(result); } } JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; @@ -92784,12 +93074,12 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { - var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); // TODO: GH#18217 if (fullMatch) { rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); } @@ -92854,12 +93144,12 @@ var ts; return undefined; } // Now, walk up our containers, adding all their names to the container array. - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { return undefined; } - declaration = ts.getContainerNode(declaration); + container = ts.getContainerNode(container); } return containers; } @@ -92882,7 +93172,7 @@ var ts; textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ // TODO: GH#18217 Just use `container ? ...` }; } })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); @@ -93216,6 +93506,7 @@ var ts; // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { + // TODO: GH#18217 return a.body.kind === b.body.kind && (a.body.kind !== 238 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ @@ -93237,7 +93528,7 @@ var ts; children.sort(compareChildren); } function compareChildren(child1, child2) { - return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217 || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); } /** @@ -93251,7 +93542,7 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName) { - return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { case 191 /* FunctionExpression */: @@ -93359,7 +93650,7 @@ var ts; } } function hasSomeImportantChild(item) { - return ts.forEach(item.children, function (child) { + return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); return childKind !== 231 /* VariableDeclaration */ && childKind !== 181 /* BindingElement */; }); @@ -93428,7 +93719,7 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 238 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 238 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217 } function isComputedProperty(member) { return !member.name || member.name.kind === 146 /* ComputedPropertyName */; @@ -93501,7 +93792,7 @@ var ts; organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; - var ambientModuleBody = getModuleBlock(ambientModule); + var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); @@ -93549,12 +93840,12 @@ var ts; OrganizeImports.organizeImports = organizeImports; function getModuleBlock(moduleDecl) { var body = moduleDecl.body; - return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -93592,8 +93883,8 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - // The JSX factory symbol is always used. - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { @@ -93619,16 +93910,16 @@ var ts; if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { // Add the namespace import to the existing default ImportDeclaration. var defaultImport = defaultImports[0]; - coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217 return coalescedImports; } var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); - }); + }); // TODO: GH#18217 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, /*name*/ undefined, namespaceImport.importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217 } if (defaultImports.length === 0 && namedImports.length === 0) { return coalescedImports; @@ -93641,10 +93932,10 @@ var ts; 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.importClause.name)); + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] @@ -93655,7 +93946,7 @@ var ts; : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) - : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); return coalescedImports; /* @@ -93749,7 +94040,8 @@ var ts; } OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier); } function sortSpecifiers(specifiers) { return ts.stableSort(specifiers, function (s1, s2) { @@ -93773,73 +94065,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); - return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { - var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; - var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); - if (newPath !== undefined) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } - }); - } - ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); - } - } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var checker = program.getTypeChecker(); - var result = []; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (!program.getSourceFileFromReference(sourceFile, ref) && ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - // If it resolved to something already, ignore. - if (checker.getSymbolAtLocation(importStringLiteral)) - continue; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } - } - return result; - } - function getPathUpdater(oldFilePath, newFilePath, host) { - // Get the relative path from old to new location, and append it on to the end of imports and normalize. - var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; - } - function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); - } -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { @@ -94075,7 +94300,7 @@ var ts; // First, check that the last part of the dot separated pattern matches the name of the // candidate. If not, then there's no point in proceeding and doing the more // expensive work. - var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments), stringToWordSpans); + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); if (!candidateMatch) { return undefined; } @@ -94808,7 +95033,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, 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 @@ -94827,7 +95052,7 @@ var ts; } } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -94899,6 +95124,7 @@ var ts; }; } function getRenameInfoError(diagnostic) { + // TODO: GH#18217 return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), @@ -94944,7 +95170,12 @@ var ts; ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); + })(ArgumentListKind || (ArgumentListKind = {})); + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + })(InvocationKind || (InvocationKind = {})); function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { var typeChecker = program.getTypeChecker(); // Decide whether to show signature help @@ -94958,11 +95189,9 @@ var ts; return undefined; cancellationToken.throwIfCancellationRequested(); // Semantic filtering of signature help - var call = argumentInfo.invocation; - var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker); cancellationToken.throwIfCancellationRequested(); - if (!candidates.length) { + if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. if (ts.isSourceFileJavaScript(sourceFile)) { @@ -94970,54 +95199,76 @@ var ts; } return undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { - if (argumentInfo.invocation.kind !== 186 /* CallExpression */) { - return undefined; + function getCandidateInfo(argumentInfo, checker) { + var invocation = argumentInfo.invocation; + if (invocation.kind === 0 /* Call */) { + var candidates = []; + var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; } + else { + var type = checker.getTypeAtLocation(invocation.called); // TODO: GH#18217 + var signatures = ts.isNewExpression(invocation.called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + var candidates = signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= argumentInfo.argumentCount; }); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + } + function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { // See if we can find some symbol with the call expression name that has call signatures. - var callExpression = argumentInfo.invocation; - var expression = callExpression.expression; + var expression = getExpressionFromInvocation(argumentInfo.invocation); var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + var _loop_16 = function (sourceFile) { var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_16 = function (declaration) { + var _loop_17 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); if (type) { var callSignatures_1 = type.getCallSignatures(); if (callSignatures_1 && callSignatures_1.length) { - return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, typeChecker); }) }; + return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; } } } }; - for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { - var declaration = declarations_12[_b]; - var state_5 = _loop_16(declaration); - if (typeof state_5 === "object") - return state_5.value; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var state_6 = _loop_17(declaration); + if (typeof state_6 === "object") + return state_6; } } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var state_5 = _loop_16(sourceFile); + if (typeof state_5 === "object") + return state_5.value; } } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.kind === 0 /* TypeArguments */ || info.invocation.kind === 1 /* TypeArgs */ ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; /** * Returns relevant information for the argument list and the current argument if we are * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (ts.isCallOrNewExpression(node.parent)) { - var invocation = node.parent; + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; var list = void 0; var argumentIndex = void 0; // There are 3 cases to handle: @@ -95037,7 +95288,7 @@ var ts; if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); + list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); ts.Debug.assert(list !== undefined); argumentIndex = 0; } @@ -95053,60 +95304,66 @@ var ts; return undefined; argumentIndex = getArgumentIndex(list, node); } - var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; + var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; var argumentCount = getArgumentCount(list); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + return { kind: kind, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 188 /* TaggedTemplateExpression */) { + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { - return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); + return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 188 /* TaggedTemplateExpression */) { - var templateExpression = node.parent; + else if (ts.isTemplateHead(node) && parent.parent.kind === 188 /* TaggedTemplateExpression */) { + var templateExpression = parent; var tagExpression = templateExpression.parent; ts.Debug.assert(templateExpression.kind === 201 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 210 /* TemplateSpan */ && node.parent.parent.parent.kind === 188 /* TaggedTemplateExpression */) { - var templateSpan = node.parent; - var templateExpression = templateSpan.parent; - var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 201 /* TemplateExpression */); + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; // If we're just after a template tail, don't show signature help. if (node.kind === 16 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } - var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position); return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent && ts.isJsxOpeningLikeElement(node.parent)) { + else if (ts.isJsxOpeningLikeElement(parent)) { // Provide a signature help for JSX opening element or JSX self-closing element. // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") // i.e // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } // 0 && ts.lastOrUndefined(listChildren).kind === 26 /* CommaToken */) { + if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -95183,7 +95440,7 @@ var ts; } return { kind: 2 /* TaggedTemplateArguments */, - invocation: tagExpression, + invocation: { kind: 0 /* Call */, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, argumentCount: argumentCount @@ -95215,7 +95472,7 @@ var ts; // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === 201 /* TemplateExpression */) { - var lastSpan = ts.lastOrUndefined(template.templateSpans); + var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } @@ -95223,39 +95480,40 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 273 /* SourceFile */; n = n.parent) { - if (ts.isFunctionBlock(n)) { - return undefined; - } + var _loop_18 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. - if (n.pos < n.parent.pos || n.end > n.parent.end) { - ts.Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); - } + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); if (argumentInfo) { - return argumentInfo; + return { value: argumentInfo }; } - // TODO: Handle generic call with incomplete syntax + }; + for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { + var state_7 = _loop_18(n); + if (typeof state_7 === "object") + return state_7.value; } return undefined; } - SignatureHelp.getContainingArgumentInfo = getContainingArgumentInfo; function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { var children = parent.getChildren(sourceFile); var indexOfOpenerToken = children.indexOf(openerToken); ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var callTarget = ts.getInvokedExpression(invocation); - var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); + var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.called; + var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); var printer = ts.createPrinter({ removeComments: true }); - var items = ts.map(candidates, function (candidateSignature) { + var items = candidates.map(function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; var suffixDisplayParts = []; @@ -95270,9 +95528,9 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); }); ts.addRange(suffixDisplayParts, parameterParts); } @@ -95280,8 +95538,8 @@ var ts; isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); - printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); } }); ts.addRange(prefixDisplayParts, typeParameterParts); @@ -95294,10 +95552,10 @@ var ts; writer.writeSpace(" "); var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); if (predicate) { - typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + typeChecker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); } else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); } }); ts.addRange(suffixDisplayParts, returnTypeParts); @@ -95319,8 +95577,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: parameter.name, @@ -95331,8 +95589,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, @@ -95362,8 +95620,7 @@ var ts; case 233 /* FunctionDeclaration */: case 191 /* FunctionExpression */: if (isJsFile) { - var symbol = node.symbol; - if (symbol.members && (symbol.members.size > 0)) { + if (node.symbol.members && (node.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)); } } @@ -95402,6 +95659,7 @@ var ts; } } } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; @@ -95412,7 +95670,7 @@ var ts; case 213 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); + }); // TODO: GH#18217 case 215 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) @@ -95432,7 +95690,7 @@ var ts; switch (node.kind) { case 243 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings.kind === 245 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 245 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; case 242 /* ImportEqualsDeclaration */: @@ -95576,7 +95834,7 @@ var ts; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - var hasAddedSymbolInfo; + var hasAddedSymbolInfo = false; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; var printer; @@ -95610,7 +95868,7 @@ var ts; } if (callExpressionLike) { var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 var useConstructSignatures = callExpressionLike.kind === 187 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { @@ -95676,7 +95934,7 @@ var ts; if (locationIsSymbolDeclaration) { var allSignatures = functionDeclaration_1.kind === 154 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; @@ -95764,12 +96022,13 @@ var ts; else { // Method/function type parameter var decl = ts.getDeclarationOfKind(symbol, 147 /* TypeParameter */); - ts.Debug.assert(decl !== undefined); + if (decl === undefined) + return ts.Debug.fail(); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); - var signature = typeChecker.getSignatureFromDeclaration(declaration); + var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 if (declaration.kind === 158 /* ConstructSignature */) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); @@ -96009,6 +96268,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0 /* None */; } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); @@ -96094,7 +96354,7 @@ var ts; options.noResolve = true; // if jsx is specified then treat file as .tsx var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); - var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217 if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } @@ -96135,7 +96395,8 @@ var ts; } // Emit program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } ts.transpileModule = transpileModule; @@ -96158,7 +96419,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_19 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -96177,7 +96438,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_19(opt); } return options; } @@ -96314,7 +96575,7 @@ var ts; lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */; } else { scanner.scan(); @@ -97068,7 +97329,7 @@ var ts; } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - context.contextNode.decorators && + !!context.contextNode.decorators && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -97373,7 +97634,7 @@ var ts; return ts.rangeContainsRange(parent.members, node); case 238 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 239 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + return !!body && body.kind === 239 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); case 273 /* SourceFile */: case 212 /* Block */: case 239 /* ModuleBlock */: @@ -97407,7 +97668,7 @@ var ts; } // pick only errors that fall in range var sorted = errors - .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217 .sort(function (e1, e2) { return e1.start - e2.start; }); if (!sorted.length) { return rangeHasNoErrors; @@ -97535,7 +97796,7 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); + processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217 trimTrailingWhitespacesForRemainingRange(); } } @@ -97896,6 +98157,7 @@ var ts; } } } + // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAction = 0 /* None */; @@ -98368,7 +98630,7 @@ var ts; // handle cases when codefix is about to be inserted before the close brace ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 : lineAtPosition !== currentStart.line ? options.indentSize : 0; - return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 } // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); @@ -98377,7 +98639,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; + return actualIndentation + options.indentSize; // TODO: GH#18217 } previous = current; current = current.parent; @@ -98674,8 +98936,9 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { case 215 /* ExpressionStatement */: case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: @@ -98697,7 +98960,6 @@ var ts; case 186 /* CallExpression */: case 187 /* NewExpression */: case 213 /* VariableStatement */: - case 231 /* VariableDeclaration */: case 248 /* ExportAssignment */: case 224 /* ReturnStatement */: case 200 /* ConditionalExpression */: @@ -98720,22 +98982,14 @@ var ts; case 246 /* NamedImports */: case 251 /* ExportSpecifier */: case 247 /* ImportSpecifier */: - case 269 /* PropertyAssignment */: case 151 /* PropertyDeclaration */: return true; - } - return false; - } - function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { - var childKind = child ? child.kind : 0 /* Unknown */; - switch (parent.kind) { case 231 /* VariableDeclaration */: case 269 /* PropertyAssignment */: - case 183 /* ObjectLiteralExpression */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183 /* ObjectLiteralExpression */) { + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } - break; + return true; case 217 /* DoStatement */: case 218 /* WhileStatement */: case 220 /* ForInStatement */: @@ -98759,6 +99013,12 @@ var ts; return childKind !== 257 /* JsxClosingElement */; case 258 /* JsxFragment */: return childKind !== 260 /* JsxClosingFragment */; + case 169 /* IntersectionType */: + case 168 /* UnionType */: + if (childKind === 165 /* TypeLiteral */) { + return false; + } + // falls through } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -98788,7 +99048,7 @@ var ts; */ function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; @@ -98905,7 +99165,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 183 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 183 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -99358,7 +99618,7 @@ var ts; var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); } return changes; }; @@ -99383,14 +99643,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_20 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_18(i); + _loop_20(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -99399,8 +99659,12 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter) { - var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; @@ -99414,7 +99678,7 @@ var ts; 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(change.options.joiner || newLineCharacter) + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217 : format(change.node); // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); @@ -99457,7 +99721,7 @@ var ts; return ts.skipTrivia(s, 0) === s.length; } function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217 // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); @@ -99877,7 +100141,7 @@ var ts; case 161 /* TypeReference */: return transformJSDocTypeReference(node); default: - var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 ts.setEmitFlags(visited, 1 /* SingleLine */); return visited; } @@ -99896,7 +100160,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 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); @@ -99981,7 +100245,7 @@ var ts; precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { - copyComments(precedingNode, newClassDeclaration, sourceFile); + copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 deleteNode(precedingNode); } else { @@ -100153,13 +100417,13 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); } } }); @@ -100167,7 +100431,7 @@ var ts; return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -100177,7 +100441,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, preferences)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -100188,14 +100452,14 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { 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); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -100230,10 +100494,10 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { switch (statement.kind) { case 213 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); return false; case 215 /* ExpressionStatement */: { var expression = statement.expression; @@ -100241,7 +100505,7 @@ var ts; case 186 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], preferences)); } return false; } @@ -100256,7 +100520,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -100269,11 +100533,11 @@ var ts; } else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); } } // Move it out to its own variable statement. (This will not be used if `!foundImport`) @@ -100285,22 +100549,22 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { switch (name.kind) { case 179 /* ObjectBindingPattern */: case 180 /* 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), + makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), 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)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } function convertAssignment(sourceFile, checker, assignment, changes, exports) { @@ -100432,7 +100696,7 @@ var ts; } function exportConst() { // `exports.x = 0;` --> `export const x = 0;` - return makeConst(modifiers, ts.createIdentifier(name), exported); + return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217 } } /** @@ -100440,16 +100704,16 @@ var ts; * 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) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { switch (name.kind) { case 179 /* 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); - }); + }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) if (importSpecifiers) { - return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, preferences)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -100460,21 +100724,21 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, preferences), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); default: - ts.Debug.assertNever(name); + return 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) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { 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(); @@ -100509,7 +100773,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -100549,10 +100813,10 @@ var ts; 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) { + function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, preferences) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -100677,7 +100941,9 @@ var ts; ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, ], - getCodeActions: getImportCodeActions, + getCodeActions: function (context) { return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(context) + : getActionsForNonUMDImport(context); }, // TODO: GH#20315 fixIds: [], getAllCodeActions: ts.notImplemented, @@ -100696,7 +100962,6 @@ var ts; program: program, checker: checker, compilerOptions: program.getCompilerOptions(), - cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(context.host)), symbolName: symbolName, symbolToken: symbolToken, @@ -100742,9 +101007,17 @@ var ts; return result; } function getCodeActionsForImport_separateExistingAndNew(exportInfos, context, useExisting, addNew) { - var existingImports = ts.flatMap(exportInfos, function (info) { - return getImportDeclarations(info, context.checker, context.sourceFile, context.cachedImportDeclarations); - }); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, context.checker, context.sourceFile); }); + ts.append(useExisting, tryUseExistingNamespaceImport(existingImports, context, context.symbolToken, context.checker)); + var addToExisting = tryAddToExistingImport(existingImports, context); + if (addToExisting) { + useExisting.push(addToExisting); + } + else { // Don't bother providing an action to add a new import if we can add to an existing one. + getCodeActionsForAddImport(exportInfos, context, existingImports, addNew); + } + } + function tryUseExistingNamespaceImport(existingImports, context, symbolToken, checker) { // It is possible that multiple import statements with the same specifier exist in the file. // e.g. // @@ -100757,19 +101030,28 @@ var ts; // 1. change "member3" to "ns.member3" // 2. add "member3" to the second import statement's import list // and it is up to the user to decide which one fits best. - if (context.symbolToken && ts.isIdentifier(context.symbolToken)) { - for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) { - var declaration = existingImports_1[_i].declaration; - var namespace_2 = getNamespaceImportName(declaration); - if (namespace_2) { - var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2)); - if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken)); - } + return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = namespace && checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { + return getCodeActionForUseExistingNamespaceImport(namespace.text, context, symbolToken); } } - } - getCodeActionsForAddImport(exportInfos, context, existingImports, useExisting, addNew); + }); + } + function tryAddToExistingImport(existingImports, context) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind === 243 /* ImportDeclaration */ && declaration.importClause) { + var changes = tryUpdateExistingImport(context, declaration.importClause, importKind); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [context.symbolName, moduleSpecifierWithoutQuotes], changes); + } + } + }); } function getNamespaceImportName(declaration) { if (declaration.kind === 243 /* ImportDeclaration */) { @@ -100780,21 +101062,14 @@ var ts; return declaration.name; } } - // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? - function getImportDeclarations(_a, checker, _b, cachedImportDeclarations) { + function getExistingImportDeclarations(_a, checker, _b) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; var imports = _b.imports; - if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } - var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (moduleSpecifier) { - var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 243 /* ImportDeclaration */ || i.kind === 242 /* ImportEqualsDeclaration */) - && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; - }); - } - return cached; + return ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 243 /* ImportDeclaration */ || i.kind === 242 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); } function getCodeActionForNewImport(context, _a) { var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; @@ -100819,7 +101094,7 @@ var ts; }); // if this file doesn't have any import statements, insert an import statement and then insert a new line // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. + // are there are already a new line separating code and import statements. return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } function shouldUseSingleQuote(sourceFile, preferences) { @@ -100853,21 +101128,7 @@ var ts; // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { - var fromExistingImport = ts.firstDefined(existingImports, function (_a) { - var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 243 /* ImportDeclaration */ && declaration.importClause) { - var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined, importKind); - if (changes) { - var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); - return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes); - } - } - }); - if (fromExistingImport) { - useExisting.push(fromExistingImport); - return; - } + function getCodeActionsForAddImport(exportInfos, ctx, existingImports, addNew) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] @@ -100889,7 +101150,7 @@ var ts; function tryUpdateExistingImport(context, importClause, importKind) { var symbolName = context.symbolName, sourceFile = context.sourceFile; var name = importClause.name; - var namedBindings = (importClause.kind !== 242 /* ImportEqualsDeclaration */ && importClause).namedBindings; + var namedBindings = (importClause.kind !== 242 /* ImportEqualsDeclaration */ && importClause).namedBindings; // TODO: GH#18217 switch (importKind) { case 1 /* Default */: return name ? undefined : ChangeTracker.with(context, function (t) { @@ -100935,11 +101196,6 @@ var ts; }); return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes); } - function getImportCodeActions(context) { - return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ? getActionsForUMDImport(context) - : getActionsForNonUMDImport(context); - } function getActionsForUMDImport(context) { var token = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); @@ -101001,7 +101257,14 @@ var ts; return undefined; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default"); - var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + var addToExistingDeclaration = []; + var addNewDeclaration = []; + getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).forEach(function (exportInfos) { + getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration); + }); + return addToExistingDeclaration.concat(addNewDeclaration); + } + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); @@ -101026,7 +101289,7 @@ var ts; addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); } function getEscapedNameForExportDefault(symbol) { - return ts.firstDefined(symbol.declarations, function (declaration) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { if (ts.isExportAssignment(declaration)) { if (ts.isIdentifier(declaration.expression)) { return declaration.expression.escapedText; @@ -101034,19 +101297,12 @@ var ts; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); - if (declaration.propertyName) { - return declaration.propertyName.escapedText; - } + return declaration.propertyName && declaration.propertyName.escapedText; } }); } }); - var addToExistingDeclaration = []; - var addNewDeclaration = []; - originalSymbolToExportInfos.forEach(function (exportInfos) { - getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration); - }); - return addToExistingDeclaration.concat(addNewDeclaration); + return originalSymbolToExportInfos; } function checkSymbolHasMeaning(_a, meaning) { var declarations = _a.declarations; @@ -101068,7 +101324,7 @@ var ts; for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { var sourceFile = allSourceFiles_1[_b]; if (ts.isExternalOrCommonJsModule(sourceFile)) { - cb(sourceFile.symbol, sourceFile); + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } @@ -101314,7 +101570,7 @@ var ts; if (token.parent.parent.kind === 199 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); // TODO: GH#18217 typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); @@ -101409,7 +101665,7 @@ var ts; var packageName = ts.getPackageName(moduleName).packageName; return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) - : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); + : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -101628,7 +101884,9 @@ var ts; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - doChange(changes, context.sourceFile, getInfo(diag.file, diag.start, diag.code)); + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); }); }, }); function getInfo(sourceFile, pos, diagCode) { @@ -101659,20 +101917,26 @@ var ts; ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { var errorCode = context.errorCode, sourceFile = context.sourceFile; - var importDecl = tryGetFullImport(sourceFile, context.span.start); + var startToken = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var importDecl = tryGetFullImport(startToken); if (importDecl) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } - var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start, /*deleted*/ undefined); }); + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, startToken, /*deleted*/ undefined); }); if (delDestructure.length) { return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(t, sourceFile, startToken, /*deleted*/ undefined); }); + if (delVar.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined); }); @@ -101688,9 +101952,10 @@ var ts; fixIds: [fixIdPrefix, fixIdDelete], getAllCodeActions: function (context) { // Track a set of deleted nodes that may be ancestors of other marked for deletion -- only delete the ancestors. - var deleted = new NodeSet(); + var deleted = new ts.NodeSet(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var sourceFile = context.sourceFile; + var startToken = ts.getTokenAtPosition(sourceFile, diag.start, /*includeJsDocComment*/ false); var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); switch (context.fixId) { case fixIdPrefix: @@ -101702,14 +101967,12 @@ var ts; // Ignore if this range was already deleted. if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); })) break; - var importDecl = tryGetFullImport(diag.file, diag.start); + var importDecl = tryGetFullImport(startToken); if (importDecl) { changes.deleteNode(sourceFile, importDecl); } - else { - if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) { - tryDeleteDeclaration(changes, sourceFile, token, deleted); - } + else if (!tryDeleteFullDestructure(changes, sourceFile, startToken, deleted) && !tryDeleteFullVariableStatement(changes, sourceFile, startToken, deleted)) { + tryDeleteDeclaration(changes, sourceFile, token, deleted); } break; default: @@ -101719,15 +101982,13 @@ var ts; }, }); // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. - function tryGetFullImport(sourceFile, pos) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + function tryGetFullImport(startToken) { return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; } - function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + function tryDeleteFullDestructure(changes, sourceFile, startToken, deletedAncestors) { if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent)) return false; - var decl = startToken.parent.parent; + var decl = ts.cast(startToken.parent, ts.isObjectBindingPattern).parent; switch (decl.kind) { case 231 /* VariableDeclaration */: tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors); @@ -101747,6 +102008,16 @@ var ts; } return true; } + function tryDeleteFullVariableStatement(changes, sourceFile, startToken, deletedAncestors) { + var declarationList = ts.tryCast(startToken.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === startToken) { + if (deletedAncestors) + deletedAncestors.add(declarationList); + changes.deleteNode(sourceFile, declarationList.parent.kind === 213 /* VariableStatement */ ? declarationList.parent : declarationList); + return true; + } + return false; + } function getToken(sourceFile, pos) { var token = ts.findPrecedingToken(pos, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); // this handles var ["computed"] = 12; @@ -101831,7 +102102,8 @@ var ts; // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + /*parameters*/ undefined, // TODO: GH#18217 + oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); // Drop leading and trailing trivia of the new function because we're only going // to replace the span (vs the full span) of the old function - the old leading // and trailing trivia will remain. @@ -101959,18 +102231,6 @@ var ts; } } } - var NodeSet = /** @class */ (function () { - function NodeSet() { - this.map = ts.createMap(); - } - NodeSet.prototype.add = function (node) { - this.map.set(String(ts.getNodeId(node)), node); - }; - NodeSet.prototype.some = function (pred) { - return ts.forEachEntry(this.map, pred) || false; - }; - return NodeSet; - }()); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -102034,6 +102294,8 @@ var ts; return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; case 237 /* EnumDeclaration */: return ts.hasModifier(s, 2048 /* Const */); + default: + return false; } } function sliceAfter(arr, value) { @@ -102120,7 +102382,7 @@ var ts; } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); @@ -102213,7 +102475,7 @@ var ts; default: return; } - return { + return insertBefore && { insertBefore: insertBefore, returnType: getReturnType(containingFunction) }; @@ -102508,7 +102770,7 @@ var ts; function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; + return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: @@ -102626,6 +102888,7 @@ var ts; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; }, reportInaccessibleThisError: notAccessible, @@ -102927,7 +103190,7 @@ var ts; return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { - var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); } @@ -102960,12 +103223,12 @@ var ts; } } if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); // TODO: GH#18217 } if (usageContext.stringIndexContext) { stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 } else { return undefined; @@ -103000,6 +103263,7 @@ var ts; parameters.push(symbol); } var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + // TODO: GH#18217 return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } function addCandidateType(context, type) { @@ -103008,7 +103272,7 @@ var ts; } } function hasCallContext(usageContext) { - return usageContext && usageContext.callContexts; + return !!usageContext && !!usageContext.callContexts; } })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); @@ -103041,7 +103305,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, context.preferences))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -103069,12 +103333,12 @@ var ts; return []; } var expr = node.expression; - var type = context.program.getTypeChecker().getTypeAtLocation(expr); + var type = context.program.getTypeChecker().getTypeAtLocation(expr); // TODO: GH#18217 if (!(type.symbol && type.symbol.originatingImport)) { return []; } var fixes = []; - var relatedImport = type.symbol.originatingImport; + var relatedImport = type.symbol.originatingImport; // TODO: GH#18217 if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } @@ -103151,8 +103415,9 @@ var ts; } 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)); + var type = propertyDeclaration.type; // TODO: GH#18217 + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); } function getActionForAddMissingInitializer(context, propertyDeclaration) { var checker = context.program.getTypeChecker(); @@ -103167,7 +103432,7 @@ var ts; changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { - return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 } function getDefaultValueFromType(checker, type) { if (type.flags & 2 /* String */) { @@ -103376,7 +103641,7 @@ var ts; // If the file is the main module, it can be imported by the package name var packageRootPath = path.substring(0, parts.packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { + if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); if (packageJsonContent) { var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; @@ -103461,7 +103726,7 @@ var ts; } function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } @@ -103527,14 +103792,14 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, 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); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { @@ -103550,8 +103815,8 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, preferences)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -103590,6 +103855,57 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + 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 token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var refactor; (function (refactor) { @@ -103672,7 +103988,7 @@ var ts; /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); - var targetRange = rangeToExtract.targetRange; + var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); if (parsedFunctionIndexMatch) { var index = +parsedFunctionIndexMatch[1]; @@ -103764,7 +104080,8 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; - for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { var errors_1 = checkNode(statement); @@ -103797,7 +104114,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -103897,6 +104214,9 @@ var ts; if (ts.isDeclaration(node)) { var declaringNode = (node.kind === 231 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { + // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) + // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! + // Also TODO: GH#19956 (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } @@ -103912,7 +104232,7 @@ var ts; // but a super *method call* simply implies a 'this' reference if (node.parent.kind === 186 /* CallExpression */) { // Super constructor call - var containingClass_1 = ts.getContainingClass(node); + var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; @@ -103923,7 +104243,7 @@ var ts; } break; } - if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { case 233 /* FunctionDeclaration */: case 234 /* ClassDeclaration */: @@ -104073,7 +104393,7 @@ var ts; function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - context.cancellationToken.throwIfCancellationRequested(); + context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217 return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { @@ -104170,7 +104490,7 @@ var ts; case 156 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: - ts.Debug.assertNever(scope); + throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { @@ -104238,7 +104558,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217 } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -104306,7 +104626,8 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), // TODO: GH#18217 + scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -104417,7 +104738,7 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -104433,7 +104754,7 @@ var ts; /*decorators*/ undefined, modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion - ? ts.createIdentifier(scope.name.getText()) + ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217 : ts.createThis(), ts.createIdentifier(localNameText)); // Declare var maxInsertionPos = node.pos; @@ -104527,7 +104848,7 @@ var ts; function getCalledExpression(scope, range, functionNameText) { var functionReference = ts.createIdentifier(functionNameText); if (ts.isClassLike(scope)) { - var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217 return ts.createPropertyAccess(lhs, functionReference); } else { @@ -104599,7 +104920,7 @@ var ts; } function getStatementsOrClassElements(scope) { if (ts.isFunctionLikeDeclaration(scope)) { - var body = scope.body; + var body = scope.body; // TODO: GH#18217 if (ts.isBlock(body)) { return body.statements; } @@ -104644,7 +104965,8 @@ var ts; } prevMember = member; } - ts.Debug.assert(prevMember !== undefined); // If the loop didn't return, then it did set prevMember. + if (prevMember === undefined) + return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember. return prevMember; } function getNodeToInsertConstantBefore(node, scope) { @@ -104671,18 +104993,15 @@ var ts; return curr.parent.parent; } // There must be at least one statement since we started in one. - ts.Debug.assert(prevStatement !== undefined); - return prevStatement; - } - if (curr === scope) { - ts.Debug.fail("Didn't encounter a block-like before encountering scope"); - break; + return ts.Debug.assertDefined(prevStatement); } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); } } function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + // TODO: GH#18217 `variableAssignments` not possibly undefined! return variableAssignments === undefined ? writeAssignments : writeAssignments === undefined @@ -104735,7 +105054,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { + else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { // TODO: GH#18217 expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -104768,7 +105087,7 @@ var ts; // will use the contextual type of an expression as the return type of the extracted // method (and will therefore "use" all the types involved). if (inGenericContext && !isReadonlyArray(targetRange.range)) { - var contextualType = checker.getContextualType(targetRange.range); + var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217 recordTypeParameterUsages(contextualType); } if (allTypeParameterUsages.size > 0) { @@ -104806,7 +105125,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_19 = function (i) { + var _loop_21 = 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 @@ -104846,7 +105165,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_19(i); + _loop_21(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -104868,7 +105187,7 @@ var ts; function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1 /* Read */; } if (inGenericContext) { - var type = checker.getTypeAtLocation(node); + var type = checker.getTypeAtLocation(node); // TODO: GH#18217 recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { @@ -105071,22 +105390,23 @@ var ts; * in the sense of something that you could extract on */ function isExtractableExpression(node) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 272 /* EnumMember */: return false; } switch (node.kind) { case 9 /* StringLiteral */: - return node.parent.kind !== 243 /* ImportDeclaration */ && - node.parent.kind !== 247 /* ImportSpecifier */; + return parent.kind !== 243 /* ImportDeclaration */ && + parent.kind !== 247 /* ImportSpecifier */; case 203 /* SpreadElement */: case 179 /* ObjectBindingPattern */: case 181 /* BindingElement */: return false; case 71 /* Identifier */: - return node.parent.kind !== 181 /* BindingElement */ && - node.parent.kind !== 247 /* ImportSpecifier */ && - node.parent.kind !== 251 /* ExportSpecifier */; + return parent.kind !== 181 /* BindingElement */ && + parent.kind !== 247 /* ImportSpecifier */ && + parent.kind !== 251 /* ExportSpecifier */; } return true; } @@ -105172,7 +105492,7 @@ var ts; var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } - function isConvertableName(name) { + function isConvertibleName(name) { return ts.isIdentifier(name) || ts.isStringLiteral(name); } function isAcceptedDeclaration(node) { @@ -105182,7 +105502,7 @@ var ts; return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name); } function createAccessorAccessExpression(fieldName, isStatic, container) { - var leftHead = isStatic ? container.name : ts.createThis(); + var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217 return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); } function getModifiers(isJS, isStatic, accessModifier) { @@ -105198,8 +105518,8 @@ var ts; var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; - if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) - || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) // TODO: GH#18217 + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; var name = declaration.name.text; var startWithUnderscore = startsWithUnderscore(name); @@ -105220,7 +105540,8 @@ var ts; function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { return ts.createGetAccessor( /*decorators*/ undefined, modifiers, accessorName, - /*parameters*/ undefined, type, ts.createBlock([ + /*parameters*/ undefined, // TODO: GH#18217 + type, ts.createBlock([ ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container)) ], /*multiLine*/ true)); } @@ -105264,7 +105585,9 @@ var ts; if (!constructor.body) return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; - var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); }); + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { + return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; var accessorName = ts.createIdentifier(fieldName.text); @@ -105287,7 +105610,7 @@ var ts; var refactorName = "Move to a new file"; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { - if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; @@ -105295,27 +105618,31 @@ var ts; getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === refactorName); var statements = ts.Debug.assertDefined(getStatementsToMove(context)); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - function getFirstAndLastStatementToMove(context) { + function getRangeToMove(context) { var file = context.file; var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); var statements = file.statements; var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); if (startNodeIndex === -1) return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return [statements[startNodeIndex]]; + } // Can't only partially include the start node or be partially into the next node - if (range.pos > statements[startNodeIndex].getStart(file)) + if (range.pos > startStatement.getStart(file)) return undefined; var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); // Can't be partially into the next node if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); } - function doChange(oldFile, program, toMove, changes, host) { + function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); @@ -105323,22 +105650,22 @@ var ts; var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. - changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); } // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. function getStatementsToMove(context) { - var statements = context.file.statements; - var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; var all = []; var ranges = []; - var rangeToMove = statements.slice(first, afterLast); ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { for (var i = start; i < afterEnd; i++) all.push(rangeToMove[i]); ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); }); - return { all: all, ranges: ranges }; + return all.length === 0 ? undefined : { all: all, ranges: ranges }; } function isPureImport(node) { switch (node.kind) { @@ -105347,7 +105674,7 @@ var ts; case 242 /* ImportEqualsDeclaration */: return !ts.hasModifier(node, 1 /* Export */); case 213 /* VariableStatement */: - return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; } @@ -105366,26 +105693,26 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { deleteMovedStatements(oldFile, toMove.ranges, changes); return toMove.all; } var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, preferences); if (importsFromNewFile) { changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); } function deleteMovedStatements(sourceFile, moved, changes) { for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { - var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last; - changes.deleteNodeRange(sourceFile, first_1, last_3); + var _a = moved_1[_i], first_1 = _a.first, last_2 = _a.last; + changes.deleteNodeRange(sourceFile, first_1, last_2); } } function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { @@ -105398,15 +105725,15 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_20 = function (sourceFile) { + var _loop_22 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_21 = function (statement) { + var _loop_23 = function (statement) { forEachImportInStatement(statement, function (importNode) { var shouldMove = function (name) { var symbol = ts.isBindingElement(name.parent) ? ts.getPropertySymbolFromBindingElement(checker, name.parent) - : ts.skipAlias(checker.getSymbolAtLocation(name), checker); + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217 return !!symbol && movedSymbols.has(symbol); }; deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file @@ -105418,12 +105745,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_21(statement); + _loop_23(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_20(sourceFile); + _loop_22(sourceFile); } } function moduleSpecifierFromImport(i) { @@ -105450,24 +105777,24 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { if (symbol.escapedName === "default" /* Default */) { - defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217 } else { imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { path = ts.ensurePathIsNonModuleName(path); if (useEs6Imports) { var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); - return ts.makeImportIfNecessary(defaultImport, specifiers, path); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, preferences); } else { ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. @@ -105566,7 +105893,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -105598,7 +105925,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -105606,7 +105933,7 @@ var ts; for (var i = 1;; i++) { var name = ts.combinePaths(inDirectory, newModuleName + extension); if (!host.fileExists(name)) - return newModuleName; + return newModuleName; // TODO: GH#18217 newModuleName = moduleName + "." + i; } } @@ -105857,7 +106184,7 @@ var ts; switch (decl.kind) { case 233 /* FunctionDeclaration */: case 234 /* ClassDeclaration */: - return [decl.name.text]; + return [decl.name.text]; // TODO: GH#18217 case 213 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); case 238 /* ModuleDeclaration */: @@ -105865,11 +106192,11 @@ var ts; case 236 /* TypeAliasDeclaration */: case 235 /* InterfaceDeclaration */: case 242 /* ImportEqualsDeclaration */: - return undefined; + return ts.emptyArray; case 215 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: - ts.Debug.assertNever(decl); + return ts.Debug.assertNever(decl); } } /** Creates `exports.x = x;` */ @@ -106089,7 +106416,7 @@ var ts; var value = 0; for (; moreDigits; state.decodingIndex++) { if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return; + return undefined; // TODO: GH#18217 } // 6 digit number var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); @@ -106139,7 +106466,7 @@ var ts; this.pos = pos; this.end = end; this.flags = 0 /* None */; - this.transformFlags = undefined; + this.transformFlags = undefined; // TODO: GH#18217 this.parent = undefined; this.kind = kind; } @@ -106325,7 +106652,7 @@ var ts; return 0; }; TokenOrIdentifierObject.prototype.getChildAt = function () { - return undefined; + return undefined; // TODO: GH#18217 }; TokenOrIdentifierObject.prototype.getChildren = function () { return ts.emptyArray; @@ -106517,9 +106844,9 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); @@ -106823,7 +107150,7 @@ var ts; }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; + return ts.isString(info) ? undefined : info; // TODO: GH#18217 }; HostCache.prototype.getRootFileNames = function () { var names = []; @@ -106841,11 +107168,11 @@ var ts; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); - return file && file.version; + return (file && file.version); // TODO: GH#18217 }; HostCache.prototype.getScriptSnapshot = function (path) { var file = this.getHostFileInformation(path); - return file && file.scriptSnapshot; + return (file && file.scriptSnapshot); // TODO: GH#18217 }; return HostCache; }()); @@ -106948,7 +107275,7 @@ var ts; this.cancellationToken = cancellationToken; } CancellationTokenObject.prototype.isCancellationRequested = function () { - return this.cancellationToken && this.cancellationToken.isCancellationRequested(); + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { @@ -106998,7 +107325,7 @@ var ts; if (!host.fileExists || !host.readFile || !host.fileExists(path)) return; // And failing that, check the disk - var text = host.readFile(path); + var text = host.readFile(path); // TODO: GH#18217 var file = { text: text, lineMap: undefined, @@ -107056,7 +107383,7 @@ var ts; var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; if (lastTypesRootVersion !== typeRootsVersion) { log("TypeRoots version has changed; provide new program"); - program = undefined; + program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } // Get a fresh cache of the host information @@ -107064,7 +107391,7 @@ var ts; var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -107141,7 +107468,7 @@ var ts; var entry = hostCache.getEntryByPath(path); return entry ? !ts.isString(entry) : - (host.fileExists && host.fileExists(fileName)); + (!!host.fileExists && host.fileExists(fileName)); } // Release any files we have acquired in the old program but are // not part of the new program. @@ -107201,6 +107528,7 @@ var ts; return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } + // TODO: GH#18217 frequently asserted as defined function getProgram() { if (syntaxOnly) { ts.Debug.assert(program === undefined); @@ -107210,14 +107538,14 @@ var ts; return program; } function cleanupSemanticCache() { - program = undefined; + program = undefined; // TODO: GH#18217 } function dispose() { if (program) { ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); - program = undefined; + program = undefined; // TODO: GH#18217 } host = undefined; } @@ -107261,7 +107589,8 @@ var ts; function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName, preferences, cancellationToken); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + getCanonicalFileName, preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -107330,7 +107659,7 @@ var ts; } function toLineColumnOffset(fileName, position) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); + var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) @@ -107397,7 +107726,7 @@ var ts; var location = possibleMapLocations_1[_i]; var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 } } return file.sourceMapper = ts.sourcemaps.identitySourceMapper; @@ -107529,11 +107858,13 @@ var ts; } /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); @@ -107560,7 +107891,7 @@ var ts; // Get node at the location var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { - return; + return undefined; } switch (node.kind) { case 184 /* PropertyAccessExpression */: @@ -107576,7 +107907,7 @@ var ts; break; // Cant create the text span default: - return; + return undefined; } var nodeForStartPos = node; while (true) { @@ -107739,7 +108070,7 @@ var ts; ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); default: - ts.Debug.fail(); + return ts.Debug.fail(); // TODO: Debug.assertNever(action); will only work if there is more than one type. } } @@ -107830,7 +108161,8 @@ var ts; descriptor = descriptors[i]; } } - ts.Debug.assert(descriptor !== undefined); + if (descriptor === undefined) + return ts.Debug.fail(); // We don't want to match something like 'TODOBY', so we make sure a non // letter/digit follows the match. if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { @@ -107995,7 +108327,7 @@ var ts; if (!sourceFile.nameTable) { initializeNameTable(sourceFile); } - return sourceFile.nameTable; + return sourceFile.nameTable; // TODO: GH#18217 } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { @@ -108049,8 +108381,8 @@ var ts; /* @internal */ function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); - return getPropertySymbolsFromType(contextualType, node.name); + var contextualType = typeChecker.getContextualType(objectLiteral); // TODO: GH#18217 + return getPropertySymbolsFromType(contextualType, node.name); // TODO: GH#18217 } ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; /* @internal */ @@ -108118,11 +108450,12 @@ var ts; // let y = 10; // token at position will return let keyword on second line as the token but we would like to use // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line - tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); // It's a blank line - if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { return undefined; } + tokenAtLocation = preceding; } // Cannot set breakpoint in ambient declarations if (tokenAtLocation.flags & 4194304 /* Ambient */) { @@ -108156,6 +108489,7 @@ var ts; } function spanInNode(node) { if (node) { + var parent = node.parent; switch (node.kind) { case 213 /* VariableStatement */: // Span on first variable declaration @@ -108258,7 +108592,7 @@ var ts; // span in statement return spanInNode(node.statement); case 149 /* Decorator */: - return spanInNodeArray(node.parent.decorators); + return spanInNodeArray(parent.decorators); case 179 /* ObjectBindingPattern */: case 180 /* ArrayBindingPattern */: return spanInBindingPattern(node); @@ -108310,7 +108644,7 @@ var ts; node.kind === 203 /* SpreadElement */ || node.kind === 269 /* PropertyAssignment */ || node.kind === 270 /* ShorthandPropertyAssignment */) && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } if (node.kind === 199 /* BinaryExpression */) { @@ -108334,7 +108668,7 @@ var ts; } } if (ts.isExpressionNode(node)) { - switch (node.parent.kind) { + switch (parent.kind) { case 217 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); @@ -108414,6 +108748,7 @@ var ts; if (variableDeclaration.parent.parent.kind === 220 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } + var parent = variableDeclaration.parent; // If this is a destructuring pattern, set breakpoint in binding pattern if (ts.isBindingPattern(variableDeclaration.name)) { return spanInBindingPattern(variableDeclaration.name); @@ -108422,7 +108757,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - variableDeclaration.parent.parent.kind === 221 /* ForOfStatement */) { + parent.parent.kind === 221 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -108709,7 +109044,7 @@ var ts; */ function transform(source, transformers, compilerOptions) { var diagnostics = []; - compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); + compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217 var nodes = ts.isArray(source) ? source : [source]; var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); @@ -108758,16 +109093,16 @@ var ts; var oldSnapshotShim = oldSnapshot; var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); if (encoded === null) { - return null; + return null; // TODO: GH#18217 } - var decoded = JSON.parse(encoded); + var decoded = JSON.parse(encoded); // TODO: GH#18217 return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; ScriptSnapshotShimAdapter.prototype.dispose = function () { // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments // 'in' does not have this effect if ("dispose" in this.scriptSnapshotShim) { - this.scriptSnapshotShim.dispose(); + this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`? } }; return ScriptSnapshotShimAdapter; @@ -108782,10 +109117,10 @@ var ts; // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { this.resolveModuleNames = function (moduleNames, containingFile) { - var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217 }); }; } @@ -108794,8 +109129,8 @@ var ts; } if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217 }; } } @@ -108815,7 +109150,7 @@ var ts; LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { if (!this.shimHost.getProjectVersion) { // shimmed host does not support getProjectVersion - return undefined; + return undefined; // TODO: GH#18217 } return this.shimHost.getProjectVersion(); }; @@ -108848,7 +109183,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { if ("getScriptKind" in this.shimHost) { - return this.shimHost.getScriptKind(fileName); + return this.shimHost.getScriptKind(fileName); // TODO: GH#18217 } else { return 0 /* Unknown */; @@ -108884,7 +109219,7 @@ var ts; return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { @@ -108905,11 +109240,11 @@ var ts; this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } if ("realpath" in this.shimHost) { - this.realpath = function (path) { return _this.shimHost.realpath(path); }; + this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -108981,7 +109316,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = /** @class */ (function (_super) { @@ -109287,10 +109623,12 @@ var ts; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); var result = ""; for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { @@ -109648,7 +109986,7 @@ var ts; } server.makeInferredProjectName = makeInferredProjectName; function createSortedArray() { - return []; + return []; // TODO: GH#19873 } server.createSortedArray = createSortedArray; })(server = ts.server || (ts.server = {})); @@ -109661,7 +109999,7 @@ var ts; function ThrottledOperations(host, logger) { this.host = host; this.pendingTimeouts = ts.createMap(); - this.logger = logger.hasLevel(server.LogLevel.verbose) && logger; + this.logger = logger.hasLevel(server.LogLevel.verbose) ? logger : undefined; } /** * Wait `number` milliseconds and then invoke `cb`. If, while waiting, schedule @@ -109707,10 +110045,10 @@ var ts; GcTimer.run = function (self) { self.timerId = undefined; var log = self.logger.hasLevel(server.LogLevel.requestTime); - var before = log && self.host.getMemoryUsage(); - self.host.gc(); + var before = log && self.host.getMemoryUsage(); // TODO: GH#18217 + self.host.gc(); // TODO: GH#18217 if (log) { - var after_1 = self.host.getMemoryUsage(); + var after_1 = self.host.getMemoryUsage(); // TODO: GH#18217 self.logger.perftrc("GC::before " + before + ", after " + after_1); } }; @@ -110160,7 +110498,7 @@ var ts; this.realpath = project.toPath(realpath); // If it is different from this.path, add to the map if (this.realpath !== this.path) { - project.projectService.realpathToScriptInfos.add(this.realpath, this); + project.projectService.realpathToScriptInfos.add(this.realpath, this); // TODO: GH#18217 } } } @@ -110358,7 +110696,7 @@ var ts; enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, - globalTypingsCacheLocation: undefined + globalTypingsCacheLocation: undefined // TODO: GH#18217 }; function setIsEqualTo(arr1, arr2) { if (arr1 === arr2) { @@ -110369,15 +110707,15 @@ var ts; } var set = ts.createMap(); var unique = 0; - for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { - var v = arr1_1[_i]; + for (var _i = 0, _a = arr1; _i < _a.length; _i++) { + var v = _a[_i]; if (set.get(v) !== true) { set.set(v, true); unique++; } } - for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { - var v = arr2_1[_a]; + for (var _b = 0, _c = arr2; _b < _c.length; _b++) { + var v = _c[_b]; var isSet = set.get(v); if (isSet === undefined) { return false; @@ -110612,7 +110950,7 @@ var ts; Project.resolveModule = function (moduleName, initialDir, host, log) { var resolvedPath = ts.normalizeSlashes(host.resolvePath(ts.combinePaths(initialDir, "node_modules"))); log("Loading " + moduleName + " from " + initialDir + " (resolved to " + resolvedPath + ")"); - var result = host.require(resolvedPath, moduleName); + var result = host.require(resolvedPath, moduleName); // TODO: GH#18217 if (result.error) { var err = result.error.stack || result.error.message || JSON.stringify(result.error); log("Failed to load module '" + moduleName + "': " + err); @@ -110679,11 +111017,11 @@ var ts; }; Project.prototype.getScriptKind = function (fileName) { var info = this.getOrCreateScriptInfoAndAttachToProject(fileName); - return info && info.scriptKind; + return (info && info.scriptKind); // TODO: GH#18217 }; Project.prototype.getScriptVersion = function (filename) { var info = this.getOrCreateScriptInfoAndAttachToProject(filename); - return info && info.getLatestVersion(); + return (info && info.getLatestVersion()); // TODO: GH#18217 }; Project.prototype.getScriptSnapshot = function (filename) { var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename); @@ -110726,14 +111064,14 @@ var ts; return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; Project.prototype.directoryExists = function (path) { - return this.directoryStructureHost.directoryExists(path); + return this.directoryStructureHost.directoryExists(path); // TODO: GH#18217 }; Project.prototype.getDirectories = function (path) { - return this.directoryStructureHost.getDirectories(path); + return this.directoryStructureHost.getDirectories(path); // TODO: GH#18217 }; /*@internal*/ Project.prototype.getCachedDirectoryStructureHost = function () { - return undefined; + return undefined; // TODO: GH#18217 }; /*@internal*/ Project.prototype.toPath = function (fileName) { @@ -110801,7 +111139,9 @@ var ts; } this.updateGraph(); this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); - return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), // TODO: GH#18217 + function (// TODO: GH#18217 + sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; /** * Returns true if emit was conducted @@ -110945,9 +111285,7 @@ var ts; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); - if (!scriptInfo) { - ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' is missing."); - } + ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' is missing."; }); return scriptInfo; }); }; @@ -111018,6 +111356,7 @@ var ts; if (info && (info.isScriptOpen() || !requireOpen)) { return this.containsScriptInfo(info); } + return false; }; Project.prototype.isRoot = function (info) { return this.rootFilesMap && this.rootFilesMap.get(info.path) === info; @@ -111170,7 +111509,7 @@ var ts; var start = ts.timestamp(); this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); this.resolutionCache.startCachingPerDirectoryResolution(); - this.program = this.languageService.getProgram(); + this.program = this.languageService.getProgram(); // TODO: GH#18217 this.dirty = false; this.resolutionCache.finishCachingPerDirectoryResolution(); ts.Debug.assert(oldProgram === undefined || this.program !== undefined); @@ -111343,7 +111682,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_22 = function (globalPluginName) { + var _loop_24 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -111358,7 +111697,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_22(globalPluginName); + _loop_24(globalPluginName); } } }; @@ -111424,6 +111763,7 @@ var ts; /*@internal*/ function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory) { var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, + // TODO: GH#18217 /*files*/ undefined, /*lastFileExceededProgramSize*/ undefined, compilerOptions, /*compileOnSaveEnabled*/ false, projectService.host, currentDirectory) || this; @@ -111661,9 +112001,9 @@ var ts; /*@internal*/ ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { if (hasFileNames) { - ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); + ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); // TODO: GH#18217 } - else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { + else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { // TODO: GH#18217 this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); } }; @@ -111835,14 +112175,14 @@ var ts; }); } } - return result; + return result; // TODO: GH#18217 }, hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, - hasMixedContent: function (x) { return x.hasMixedContent; }, + hasMixedContent: function (x) { return !!x.hasMixedContent; }, }; function findProjectByName(projectName, projects) { for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { @@ -111948,10 +112288,11 @@ var ts; if (this.host.realpath) { this.realpathToScriptInfos = ts.createMultiMap(); } - this.currentDirectory = this.host.getCurrentDirectory(); + this.currentDirectory = server.toNormalizedPath(this.host.getCurrentDirectory()); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); - this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation && - ts.ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)); + this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation + ? ts.ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)) + : undefined; this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); if (this.typesMapLocation) { this.loadTypesMap(); @@ -111967,7 +112308,7 @@ var ts; hostInfo: "Unknown host", extraFileExtensions: [] }; - this.documentRegistry = ts.createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.currentDirectory); + this.documentRegistry = ts.createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this); var watchLogLevel = this.logger.hasLevel(server.LogLevel.verbose) ? ts.WatchLogLevel.Verbose : this.logger.loggingEnabled() ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None; var log = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return _this.logger.info(s); }) : ts.noop; @@ -111984,6 +112325,16 @@ var ts; ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); }; + /*@internal*/ + ProjectService.prototype.setDocument = function (key, path, sourceFile) { + var info = ts.Debug.assertDefined(this.getScriptInfoForPath(path)); + info.cacheSourceFile = { key: key, sourceFile: sourceFile }; + }; + /*@internal*/ + ProjectService.prototype.getDocument = function (key, path) { + var info = this.getScriptInfoForPath(path); + return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : undefined; + }; /* @internal */ ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { this.ensureProjectStructuresUptoDate(); @@ -112005,7 +112356,7 @@ var ts; }; ProjectService.prototype.loadTypesMap = function () { try { - var fileContent = this.host.readFile(this.typesMapLocation); + var fileContent = this.host.readFile(this.typesMapLocation); // TODO: GH#18217 if (fileContent === undefined) { this.logger.info("Provided types map file \"" + this.typesMapLocation + "\" doesn't exist"); return; @@ -112160,7 +112511,7 @@ var ts; } return scriptInfo.getDefaultProject(); } - return scriptInfo && !scriptInfo.isOrphan() && scriptInfo.getDefaultProject(); + return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined; }; ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { this.ensureProjectStructuresUptoDate(); @@ -112325,7 +112676,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_23 = function (inferredProject) { + var _loop_25 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -112346,7 +112697,7 @@ var ts; // Note that we need to create a copy of the array since the list of project can change for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_23(inferredProject); + _loop_25(inferredProject); } } return project; @@ -112421,7 +112772,7 @@ var ts; this.filenameToScriptInfo.delete(info.path); var realpath = info.getRealpathIfDifferent(); if (realpath) { - this.realpathToScriptInfos.remove(realpath, info); + this.realpathToScriptInfos.remove(realpath, info); // TODO: GH#18217 } }; ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { @@ -112717,7 +113068,7 @@ var ts; }; ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); + var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 var result = ts.parseJsonText(configFilename, configFileContent); if (!result.endOfFileToken) { result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; @@ -112776,7 +113127,7 @@ var ts; var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) .filter(function (name) { return hasTypeScriptFileExtension(name); }) - .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) + .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217 .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); } @@ -112819,7 +113170,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject && project.getConfigFilePath(); + var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; // TODO: GH#18217 return server.getBaseConfigFileName(configFilePath) || "other"; } function convertTypeAcquisition(_a) { @@ -112839,20 +113190,21 @@ var ts; }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; - var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217 var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, // TODO: GH#18217 + lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); project.configFileSpecs = configFileSpecs; // TODO: We probably should also watch the configFiles that are extended project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); + project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 } project.setProjectErrors(configFileErrors); var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); + this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); // TODO: GH#18217 this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); this.sendProjectTelemetry(configFileName, project, projectOptions); @@ -112881,7 +113233,7 @@ var ts; else { var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); + scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); // TODO: GH#18217 path = scriptInfo.path; // If this script info is not already a root add it if (!project.isRoot(scriptInfo)) { @@ -112927,7 +113279,7 @@ var ts; */ /*@internal*/ ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { - var configFileSpecs = project.configFileSpecs; + var configFileSpecs = project.configFileSpecs; // TODO: GH#18217 var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); @@ -112951,16 +113303,16 @@ var ts; project.configFileSpecs = configFileSpecs; project.setProjectErrors(configFileErrors); project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 if (lastFileExceededProgramSize) { project.disableLanguageService(lastFileExceededProgramSize); project.stopWatchingWildCards(); } else { project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); + project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); // TODO: GH#18217 this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { @@ -113074,7 +113426,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_24 = function (project) { + var _loop_26 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -113091,7 +113443,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_24(project); + _loop_26(project); } } } @@ -113139,7 +113491,7 @@ var ts; if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; } - info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, path); + info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path); // TODO: GH#18217 this.filenameToScriptInfo.set(info.path, info); if (!openedByClient) { this.watchClosedScriptInfo(info); @@ -113244,7 +113596,7 @@ var ts; if (!shouldReloadProjectFor(openFileValue)) { return; } - var info = _this.getScriptInfoForPath(path); + var info = _this.getScriptInfoForPath(path); // TODO: GH#18217 ts.Debug.assert(info.isScriptOpen()); // This tries to search for a tsconfig.json for the given file. If we found it, // we first detect if there is already a configured project created for it: if so, @@ -113342,7 +113694,7 @@ var ts; var _this = this; var configFileName; var configFileErrors; - var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); + var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217 this.openFiles.set(info.path, projectRootPath); var project = this.findExternalProjectContainingOpenScriptInfo(info); if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization @@ -113430,13 +113782,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_25 = function (proj) { - var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); + var _loop_27 = function (proj) { + var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_25(proj); + _loop_27(proj); } }; /* @internal */ @@ -113455,7 +113807,7 @@ var ts; var scriptInfo = this.getScriptInfo(file_21.fileName); ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already"); var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file_21.fileName); - this.openClientFileWithNormalizedPath(normalizedPath, file_21.content, tryConvertScriptKindName(file_21.scriptKind), file_21.hasMixedContent); + this.openClientFileWithNormalizedPath(normalizedPath, file_21.content, tryConvertScriptKindName(file_21.scriptKind), file_21.hasMixedContent); // TODO: GH#18217 } } if (changedFiles) { @@ -113535,7 +113887,8 @@ var ts; }; ProjectService.prototype.applySafeList = function (proj) { var _this = this; - var rootFiles = proj.rootFiles, typeAcquisition = proj.typeAcquisition; + var rootFiles = proj.rootFiles; + var typeAcquisition = proj.typeAcquisition; ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); // If type acquisition has been explicitly disabled, do not exclude anything from the project if (typeAcquisition.enable === false) { @@ -113545,7 +113898,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_26 = function (name) { + var _loop_28 = function (name) { var rule_2 = this_2.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -113563,7 +113916,7 @@ var ts; } } if (rule_2.exclude) { - var _loop_28 = function (exclude) { + var _loop_30 = function (exclude) { var processedRule = root.replace(rule_2.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -113590,7 +113943,7 @@ var ts; }; for (var _c = 0, _d = rule_2.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_28(exclude); + _loop_30(exclude); } } else { @@ -113606,11 +113959,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_26(name); + _loop_28(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_27 = function (i) { + var _loop_29 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -113648,7 +114001,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_27(i); + _loop_29(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -113763,7 +114116,7 @@ var ts; } }; ProjectService.prototype.hasDeferredExtension = function () { - for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { + for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { // TODO: GH#18217 var extension = _a[_i]; if (extension.scriptKind === 7 /* Deferred */) { return true; @@ -113832,7 +114185,7 @@ var ts; } } function formatDiag(fileName, project, diag) { - var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); // TODO: GH#18217 return { start: scriptInfo.positionToLineOffset(diag.start), end: scriptInfo.positionToLineOffset(diag.start + diag.length), @@ -113847,8 +114200,8 @@ var ts; return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; } function formatConfigFileDiag(diag, includeFileName) { - var start = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start)); - var end = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length)); + var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start))); // TODO: GH#18217 + var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length))); // TODO: GH#18217 var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n"); var code = diag.code, source = diag.source; var category = ts.diagnosticCategoryName(diag); @@ -114025,7 +114378,7 @@ var ts; }, _a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) { _this.changeSeq++; - _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); // TODO: GH#18217 // TODO: report errors return _this.requiredResponse(/*response*/ true); }, @@ -114070,7 +114423,8 @@ var ts; return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[server.CommandNames.Open] = function (request) { - _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined); + _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), // TODO: GH#18217 + request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined); return _this.notRequired(); }, _a[server.CommandNames.Quickinfo] = function (request) { @@ -114287,6 +114641,7 @@ var ts; this.logger = opts.logger; this.canUseEvents = opts.canUseEvents; this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate; var throttleWaitMilliseconds = opts.throttleWaitMilliseconds; this.eventHandler = this.canUseEvents ? opts.eventHandler || (function (event) { return _this.defaultEventHandler(event); }) @@ -114358,7 +114713,7 @@ var ts; var _this = this; this.projectService.logger.info("got projects updated in background, updating diagnostics for " + openFiles); if (openFiles.length) { - if (!this.suppressDiagnosticEvents) { + if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { var checkList_1 = this.createCheckList(openFiles); // For now only queue error checking for open files. We can change this to include non open files as well this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, /*requireOpen*/ true); }); @@ -114394,7 +114749,7 @@ var ts; // For backwards-compatibility only. /** @deprecated */ Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { - this.doOutput(info, cmdName, reqSeq, /*success*/ !errorMsg, errorMsg); + this.doOutput(info, cmdName, reqSeq, /*success*/ !errorMsg, errorMsg); // TODO: GH#18217 }; Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) { var res = { @@ -114505,20 +114860,20 @@ var ts; return project.getLanguageService().getEncodedSemanticClassifications(file, args); }; Session.prototype.getProject = function (projectFileName) { - return projectFileName && this.projectService.findProject(projectFileName); + return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName); }; Session.prototype.getConfigFileAndProject = function (args) { var project = this.getProject(args.projectFileName); var file = server.toNormalizedPath(args.file); return { - configFile: project && project.hasConfigFile(file) && file, + configFile: project && project.hasConfigFile(file) ? file : undefined, project: project }; }; Session.prototype.getConfigFileDiagnostics = function (configFile, project, includeLinePosition) { var projectErrors = project.getAllProjectErrors(); var optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); - var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return diagnostic.file && diagnostic.file.fileName === configFile; }); + var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return !!diagnostic.file && diagnostic.file.fileName === configFile; }); return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ false); }); @@ -114531,8 +114886,8 @@ var ts; length: d.length, 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)) + startLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start))), + endLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length))) // TODO: GH#18217 }); }); }; Session.prototype.getCompilerOptionsDiagnostics = function (args) { @@ -114588,7 +114943,7 @@ var ts; if (!definitionAndBoundSpan || !definitionAndBoundSpan.definitions) { return { definitions: server.emptyArray, - textSpan: undefined + textSpan: undefined // TODO: GH#18217 }; } if (simplifiedResult) { @@ -114619,7 +114974,7 @@ var ts; }; Session.prototype.toFileSpan = function (fileName, textSpan, project) { var ls = project.getLanguageService(); - var start = ls.toLineColumnOffset(fileName, textSpan.start); + var start = ls.toLineColumnOffset(fileName, textSpan.start); // TODO: GH#18217 var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan)); return { file: fileName, @@ -114681,14 +115036,14 @@ var ts; // all the config file errors are reported as part of semantic check so nothing to report here return server.emptyArray; } - return this.getDiagnosticsWorker(args, /*isSemantic*/ false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); + return this.getDiagnosticsWorker(args, /*isSemantic*/ false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project; if (configFile) { - return this.getConfigFileDiagnostics(configFile, project, args.includeLinePosition); + return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); // TODO: GH#18217 } - return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); + 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; @@ -114697,7 +115052,7 @@ var ts; 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); + 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; @@ -114767,7 +115122,7 @@ var ts; if ((!projects || !projects.length) && !symLinkedProjects) { return server.Errors.ThrowNoProject(); } - return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; + return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; // TODO: GH#18217 }; Session.prototype.getDefaultProject = function (args) { if (args.projectFileName) { @@ -114953,7 +115308,7 @@ var ts; }; Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) { var file = server.toNormalizedPath(uncheckedFileName); - var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, /*ensureProject*/ true); + var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, /*ensureProject*/ true); // TODO: GH#18217 return { file: file, project: project }; }; Session.prototype.getOutliningSpans = function (args, simplifiedResult) { @@ -115051,7 +115406,7 @@ var ts; Session.prototype.getFormattingEditsForRangeFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); - return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); + return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); // TODO: GH#18217 }; Session.prototype.getFormattingEditsForDocumentFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -115061,7 +115416,7 @@ var ts; Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); - return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); // TODO: GH#18217 }; Session.prototype.getFormattingEditsAfterKeystroke = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -115086,7 +115441,7 @@ var ts; hasIndent++; } else if (lineText.charAt(i) === "\t") { - hasIndent += formatOptions.tabSize; + hasIndent += formatOptions.tabSize; // TODO: GH#18217 } else { break; @@ -115232,13 +115587,13 @@ var ts; this.changeSeq++; this.projectService.applyChangesToFile(scriptInfo, [{ span: { start: start, length: end - start }, - newText: args.insertString + newText: args.insertString // TODO: GH#18217 }]); } }; Session.prototype.reload = function (args, reqSeq) { var file = server.toNormalizedPath(args.file); - var tempFileName = args.tmpfile && server.toNormalizedPath(args.tmpfile); + var tempFileName = args.tmpfile === undefined ? undefined : server.toNormalizedPath(args.tmpfile); var info = this.projectService.getScriptInfoForNormalizedPath(file); if (info) { this.changeSeq++; @@ -115396,7 +115751,7 @@ var ts; var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; textRange = { pos: startPosition, end: endPosition }; } - return { position: position, textRange: textRange }; + return { position: position, textRange: textRange }; // TODO: GH#18217 function getPosition(loc) { return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); } @@ -115449,7 +115804,7 @@ var ts; }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { var _this = this; - if (args.errorCodes.length === 0) { + if (args.errorCodes.length === 0) { // TODO: GH#18217 return undefined; } var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; @@ -115557,7 +115912,7 @@ var ts; return; } // No need to analyze lib.d.ts - var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); + var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); // TODO: GH#18217 if (fileNamesInProject.length === 0) { return; } @@ -115574,7 +115929,7 @@ var ts; highPriorityFiles.push(fileNameInProject); } else { - var info = this.projectService.getScriptInfo(fileNameInProject); + var info = this.projectService.getScriptInfo(fileNameInProject); // TODO: GH#18217 if (!info.isScriptOpen()) { if (ts.fileExtensionIs(fileNameInProject, ".d.ts" /* Dts */)) { veryLowPriorityFiles.push(fileNameInProject); @@ -115618,7 +115973,7 @@ var ts; }; Session.prototype.resetCurrentRequest = function (requestId) { ts.Debug.assert(this.currentRequestId === requestId); - this.currentRequestId = undefined; + this.currentRequestId = undefined; // TODO: GH#18217 this.cancellationToken.resetRequest(requestId); }; Session.prototype.executeWithRequestId = function (requestId, f) { @@ -116000,7 +116355,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[this.versionToIndex(i)]; + var snap = this.versions[this.versionToIndex(i)]; // TODO: GH#18217 for (var _i = 0, _a = snap.changesSincePreviousVersion; _i < _a.length; _i++) { var textChange = _a[_i]; textChangeRanges.push(textChange.getTextChangeRange()); @@ -116136,6 +116491,7 @@ var ts; this.load(LineIndex.linesFromText(newText).lines); return this; } + return undefined; // TODO: GH#18217 } else { var checkText = void 0; @@ -116164,7 +116520,7 @@ var ts; var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText; if (zeroBasedColumn === 0) { // move range end just past line that will merge with previous line - deleteLength += lineText.length; + deleteLength += lineText.length; // TODO: GH#18217 // store text by appending to end of insertedText newText = newText ? newText + lineText : lineText; } diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index b449fc853c6..ddc50646c07 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -460,7 +460,7 @@ declare namespace ts { flags: NodeFlags; decorators?: NodeArray; modifiers?: ModifiersArray; - parent?: Node; + parent: Node; } interface JSDocContainer { } @@ -525,12 +525,12 @@ declare namespace ts { } interface Decorator extends Node { kind: SyntaxKind.Decorator; - parent?: NamedDeclaration; + parent: NamedDeclaration; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; - parent?: DeclarationWithTypeParameters | InferTypeNode; + parent: DeclarationWithTypeParameters | InferTypeNode; name: Identifier; constraint?: TypeNode; default?: TypeNode; @@ -541,7 +541,7 @@ declare namespace ts { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; - type: TypeNode | undefined; + type?: TypeNode; } type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { @@ -553,7 +553,7 @@ declare namespace ts { type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; - parent?: VariableDeclarationList | CatchClause; + parent: VariableDeclarationList | CatchClause; name: BindingName; exclamationToken?: ExclamationToken; type?: TypeNode; @@ -561,12 +561,12 @@ declare namespace ts { } interface VariableDeclarationList extends Node { kind: SyntaxKind.VariableDeclarationList; - parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; + parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.Parameter; - parent?: SignatureDeclaration; + parent: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; name: BindingName; questionToken?: QuestionToken; @@ -575,7 +575,7 @@ declare namespace ts { } interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; - parent?: BindingPattern; + parent: BindingPattern; propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: BindingName; @@ -628,12 +628,12 @@ declare namespace ts { } interface ObjectBindingPattern extends Node { kind: SyntaxKind.ObjectBindingPattern; - parent?: VariableDeclaration | ParameterDeclaration | BindingElement; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; elements: NodeArray; } interface ArrayBindingPattern extends Node { kind: SyntaxKind.ArrayBindingPattern; - parent?: VariableDeclaration | ParameterDeclaration | BindingElement; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; elements: NodeArray; } type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; @@ -662,41 +662,41 @@ declare namespace ts { } interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; - parent?: ObjectTypeDeclaration; + parent: ObjectTypeDeclaration; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.MethodDeclaration; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassLikeDeclaration; + parent: ClassLikeDeclaration; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassLikeDeclaration; + parent: ClassLikeDeclaration; } interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ObjectTypeDeclaration; + parent: ObjectTypeDeclaration; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -730,7 +730,7 @@ declare namespace ts { } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; - parent?: SignatureDeclaration; + parent: SignatureDeclaration; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -959,15 +959,15 @@ declare namespace ts { } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; - parent?: TemplateExpression; + parent: TemplateExpression; } interface TemplateMiddle extends LiteralLikeNode { kind: SyntaxKind.TemplateMiddle; - parent?: TemplateSpan; + parent: TemplateSpan; } interface TemplateTail extends LiteralLikeNode { kind: SyntaxKind.TemplateTail; - parent?: TemplateSpan; + parent: TemplateSpan; } type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { @@ -977,7 +977,7 @@ declare namespace ts { } interface TemplateSpan extends Node { kind: SyntaxKind.TemplateSpan; - parent?: TemplateExpression; + parent: TemplateExpression; expression: Expression; literal: TemplateMiddle | TemplateTail; } @@ -991,7 +991,7 @@ declare namespace ts { } interface SpreadElement extends Expression { kind: SyntaxKind.SpreadElement; - parent?: ArrayLiteralExpression | CallExpression | NewExpression; + parent: ArrayLiteralExpression | CallExpression | NewExpression; expression: Expression; } /** @@ -1044,7 +1044,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent?: HeritageClause; + parent: HeritageClause; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1090,11 +1090,11 @@ declare namespace ts { type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxAttributes extends ObjectLiteralExpressionBase { - parent?: JsxOpeningLikeElement; + parent: JsxOpeningLikeElement; } interface JsxOpeningElement extends Expression { kind: SyntaxKind.JsxOpeningElement; - parent?: JsxElement; + parent: JsxElement; tagName: JsxTagNameExpression; typeArguments?: NodeArray; attributes: JsxAttributes; @@ -1113,38 +1113,38 @@ declare namespace ts { } interface JsxOpeningFragment extends Expression { kind: SyntaxKind.JsxOpeningFragment; - parent?: JsxFragment; + parent: JsxFragment; } interface JsxClosingFragment extends Expression { kind: SyntaxKind.JsxClosingFragment; - parent?: JsxFragment; + parent: JsxFragment; } interface JsxAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxAttribute; - parent?: JsxAttributes; + parent: JsxAttributes; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxSpreadAttribute; - parent?: JsxAttributes; + parent: JsxAttributes; expression: Expression; } interface JsxClosingElement extends Node { kind: SyntaxKind.JsxClosingElement; - parent?: JsxElement; + parent: JsxElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { kind: SyntaxKind.JsxExpression; - parent?: JsxElement | JsxAttributeLike; + parent: JsxElement | JsxAttributeLike; dotDotDotToken?: Token; expression?: Expression; } interface JsxText extends Node { kind: SyntaxKind.JsxText; containsOnlyWhiteSpaces: boolean; - parent?: JsxElement; + parent: JsxElement; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; interface Statement extends Node { @@ -1245,18 +1245,18 @@ declare namespace ts { } interface CaseBlock extends Node { kind: SyntaxKind.CaseBlock; - parent?: SwitchStatement; + parent: SwitchStatement; clauses: NodeArray; } interface CaseClause extends Node { kind: SyntaxKind.CaseClause; - parent?: CaseBlock; + parent: CaseBlock; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { kind: SyntaxKind.DefaultClause; - parent?: CaseBlock; + parent: CaseBlock; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; @@ -1267,7 +1267,7 @@ declare namespace ts { } interface ThrowStatement extends Statement { kind: SyntaxKind.ThrowStatement; - expression: Expression; + expression?: Expression; } interface TryStatement extends Statement { kind: SyntaxKind.TryStatement; @@ -1277,7 +1277,7 @@ declare namespace ts { } interface CatchClause extends Node { kind: SyntaxKind.CatchClause; - parent?: TryStatement; + parent: TryStatement; variableDeclaration?: VariableDeclaration; block: Block; } @@ -1317,7 +1317,7 @@ declare namespace ts { } interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassLikeDeclaration; + parent: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -1329,7 +1329,7 @@ declare namespace ts { } interface EnumMember extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.EnumMember; - parent?: EnumDeclaration; + parent: EnumDeclaration; name: PropertyName; initializer?: Expression; } @@ -1342,7 +1342,7 @@ declare namespace ts { type ModuleBody = NamespaceBody | JSDocNamespaceBody; interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ModuleDeclaration; - parent?: ModuleBody | SourceFile; + parent: ModuleBody | SourceFile; name: ModuleName; body?: ModuleBody | JSDocNamespaceDeclaration; } @@ -1354,11 +1354,11 @@ declare namespace ts { type JSDocNamespaceBody = Identifier | JSDocNamespaceDeclaration; interface JSDocNamespaceDeclaration extends ModuleDeclaration { name: Identifier; - body: JSDocNamespaceBody; + body?: JSDocNamespaceBody; } interface ModuleBlock extends Node, Statement { kind: SyntaxKind.ModuleBlock; - parent?: ModuleDeclaration; + parent: ModuleDeclaration; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; @@ -1369,18 +1369,18 @@ declare namespace ts { */ interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ImportEqualsDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { kind: SyntaxKind.ExternalModuleReference; - parent?: ImportEqualsDeclaration; - expression?: Expression; + parent: ImportEqualsDeclaration; + expression: Expression; } interface ImportDeclaration extends Statement { kind: SyntaxKind.ImportDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; importClause?: ImportClause; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier: Expression; @@ -1388,13 +1388,13 @@ declare namespace ts { type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; - parent?: ImportDeclaration; + parent: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; - parent?: ImportClause; + parent: ImportClause; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { @@ -1403,7 +1403,7 @@ declare namespace ts { } interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ @@ -1411,24 +1411,24 @@ declare namespace ts { } interface NamedImports extends Node { kind: SyntaxKind.NamedImports; - parent?: ImportClause; + parent: ImportClause; elements: NodeArray; } interface NamedExports extends Node { kind: SyntaxKind.NamedExports; - parent?: ExportDeclaration; + parent: ExportDeclaration; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; - parent?: NamedImports; + parent: NamedImports; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; - parent?: NamedExports; + parent: NamedExports; propertyName?: Identifier; name: Identifier; } @@ -1439,7 +1439,7 @@ declare namespace ts { */ interface ExportAssignment extends DeclarationStatement { kind: SyntaxKind.ExportAssignment; - parent?: SourceFile; + parent: SourceFile; isExportEquals?: boolean; expression: Expression; } @@ -1494,15 +1494,15 @@ declare namespace ts { type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; - parent?: HasJSDoc; - tags: NodeArray | undefined; - comment: string | undefined; + parent: HasJSDoc; + tags?: NodeArray; + comment?: string; } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; atToken: AtToken; tagName: Identifier; - comment: string | undefined; + comment?: string; } interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; @@ -1526,11 +1526,11 @@ declare namespace ts { } interface JSDocReturnTag extends JSDocTag { kind: SyntaxKind.JSDocReturnTag; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { kind: SyntaxKind.JSDocTypeTag; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { parent: JSDoc; @@ -1608,7 +1608,7 @@ declare namespace ts { container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNodeBase { - antecedents: FlowNode[]; + antecedents: FlowNode[] | undefined; } interface FlowAssignment extends FlowNodeBase { node: Expression | VariableDeclaration | BindingElement; @@ -1635,7 +1635,7 @@ declare namespace ts { } interface AmdDependency { path: string; - name: string; + name?: string; } interface SourceFile extends Declaration { kind: SyntaxKind.SourceFile; @@ -1644,7 +1644,7 @@ declare namespace ts { fileName: string; text: string; amdDependencies: ReadonlyArray; - moduleName: string; + moduleName?: string; referencedFiles: ReadonlyArray; typeReferenceDirectives: ReadonlyArray; languageVariant: LanguageVariant; @@ -1704,7 +1704,7 @@ declare namespace ts { fileExists(path: string): boolean; readFile(path: string): string | undefined; } - type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray) => void; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { @@ -1734,9 +1734,10 @@ declare namespace ts { emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. @@ -1793,7 +1794,7 @@ declare namespace ts { emitSkipped: boolean; /** Contains declaration emit diagnostics */ diagnostics: ReadonlyArray; - emittedFiles: string[]; + emittedFiles?: string[]; } interface TypeChecker { getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; @@ -1810,7 +1811,7 @@ declare namespace ts { getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; + typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; @@ -1846,7 +1847,7 @@ declare namespace ts { */ getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; - getTypeAtLocation(node: Node): Type; + getTypeAtLocation(node: Node): Type | undefined; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; @@ -1863,9 +1864,10 @@ declare namespace ts { getContextualType(node: Expression): Type | undefined; /** * returns unknownSignature in the case of an error. + * returns undefined if the node is not valid. * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. */ - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; @@ -2069,8 +2071,8 @@ declare namespace ts { interface Symbol { flags: SymbolFlags; escapedName: __String; - declarations?: Declaration[]; - valueDeclaration?: Declaration; + declarations: Declaration[]; + valueDeclaration: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; @@ -2172,15 +2174,15 @@ declare namespace ts { type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { flags: TypeFlags; - symbol?: Symbol; + symbol: Symbol; pattern?: DestructuringPattern; aliasSymbol?: Symbol; aliasTypeArguments?: Type[]; } interface LiteralType extends Type { value: string | number; - freshType?: LiteralType; - regularType?: LiteralType; + freshType: LiteralType; + regularType: LiteralType; } interface UniqueESSymbolType extends Type { symbol: Symbol; @@ -2215,18 +2217,18 @@ declare namespace ts { } /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[]; - outerTypeParameters: TypeParameter[]; - localTypeParameters: TypeParameter[]; - thisType: TypeParameter; + typeParameters: TypeParameter[] | undefined; + outerTypeParameters: TypeParameter[] | undefined; + localTypeParameters: TypeParameter[] | undefined; + thisType: TypeParameter | undefined; } type BaseType = ObjectType | IntersectionType; interface InterfaceTypeWithDeclaredMembers extends InterfaceType { declaredProperties: Symbol[]; declaredCallSignatures: Signature[]; declaredConstructSignatures: Signature[]; - declaredStringIndexInfo: IndexInfo; - declaredNumberIndexInfo: IndexInfo; + declaredStringIndexInfo?: IndexInfo; + declaredNumberIndexInfo?: IndexInfo; } /** * Type references (ObjectFlags.Reference). When a class or interface has type parameters or @@ -2277,11 +2279,11 @@ declare namespace ts { trueType: Type; falseType: Type; isDistributive: boolean; - inferTypeParameters: TypeParameter[]; + inferTypeParameters?: TypeParameter[]; outerTypeParameters?: TypeParameter[]; instantiations?: Map; - aliasSymbol: Symbol; - aliasTypeArguments: Type[]; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; } interface ConditionalType extends InstantiableType { root: ConditionalRoot; @@ -2359,6 +2361,11 @@ declare namespace ts { code: number; source?: string; } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; + } enum DiagnosticCategory { Warning = 0, Error = 1, @@ -2447,6 +2454,7 @@ declare namespace ts { sourceMap?: boolean; sourceRoot?: string; strict?: boolean; + strictAny?: boolean; strictFunctionTypes?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; @@ -2624,7 +2632,7 @@ declare namespace ts { packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { - readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; readonly failedLookupLocations: ReadonlyArray; } interface CompilerHost extends ModuleResolutionHost { @@ -2644,8 +2652,8 @@ declare namespace ts { /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; - getEnvironmentVariable?(name: string): string; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; } interface SourceMapRange extends TextRange { @@ -2657,6 +2665,7 @@ declare namespace ts { skipTrivia?: (pos: number) => number; } enum EmitFlags { + None = 0, SingleLine = 1, AdviseOnEmitNode = 2, NoSubstitution = 4, @@ -2710,7 +2719,7 @@ declare namespace ts { /** Resumes a suspended lexical environment, usually before visiting a function body. */ resumeLexicalEnvironment(): void; /** Ends a lexical environment, returning any declarations. */ - endLexicalEnvironment(): Statement[]; + endLexicalEnvironment(): Statement[] | undefined; /** Hoists a function declaration to the containing scope. */ hoistFunctionDeclaration(node: FunctionDeclaration): void; /** Hoists a variable declaration to the containing scope. */ @@ -2754,7 +2763,7 @@ declare namespace ts { /** Gets the transformed source files. */ transformed: T[]; /** Gets diagnostics for the transformation. */ - diagnostics?: Diagnostic[]; + diagnostics?: DiagnosticWithLocation[]; /** * Gets a substitute for a node, if one is available; otherwise, returns the original node. * @@ -2841,7 +2850,7 @@ declare namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -2954,13 +2963,13 @@ declare namespace ts { } } declare namespace ts { - const versionMajorMinor = "2.9"; + const versionMajorMinor = "3.0"; /** The version of the TypeScript compiler release */ const version: string; } declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): Diagnostic[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3014,7 +3023,7 @@ declare namespace ts { interface FileWatcher { close(): void; } - function getNodeMajorVersion(): number; + function getNodeMajorVersion(): number | undefined; let sys: System; } declare namespace ts { @@ -3041,8 +3050,8 @@ declare namespace ts { scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; - setText(text: string, start?: number, length?: number): void; - setOnError(onError: ErrorCallback): void; + setText(text: string | undefined, start?: number, length?: number): void; + setOnError(onError: ErrorCallback | undefined): void; setScriptTarget(scriptTarget: ScriptTarget): void; setLanguageVariant(variant: LanguageVariant): void; setTextPos(textPos: number): void; @@ -3062,15 +3071,15 @@ declare namespace ts { function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; - function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; - function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ function getShebang(text: string): string | undefined; - function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -3079,12 +3088,12 @@ declare namespace ts { function textSpanContainsPosition(span: TextSpan, position: number): boolean; function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined; function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined; function createTextSpan(start: number, length: number): TextSpan; function createTextSpanFromBounds(start: number, end: number): TextSpan; function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; @@ -3100,7 +3109,7 @@ declare namespace ts { * Vn. */ function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration; + function getTypeParameterOwner(d: Declaration): Declaration | undefined; type ParameterPropertyDeclaration = ParameterDeclaration & { parent: ConstructorDeclaration; name: Identifier; @@ -3122,6 +3131,8 @@ declare namespace ts { }, errors?: Push): void; function getOriginalNode(node: Node): Node; function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + function getOriginalNode(node: Node | undefined): Node | undefined; + function getOriginalNode(node: Node | undefined, nodeTest: (node: Node | undefined) => node is T): T | undefined; /** * Gets a value indicating whether a node originated in the parse tree. * @@ -3142,7 +3153,7 @@ declare namespace ts { * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. * @returns The original parse tree node if found; otherwise, undefined. */ - function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; + function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; /** * Remove extra underscore from escaped identifier text content. * @@ -3160,7 +3171,7 @@ declare namespace ts { */ function unescapeIdentifier(id: string): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; - function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName; /** * Gets the JSDoc parameter tags for the node if present. * @@ -3442,7 +3453,7 @@ declare namespace ts { */ function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; - function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined; /** * Parse json text into SyntaxTree and return node and parse errors if any * @param fileName @@ -3488,7 +3499,7 @@ declare namespace ts { getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; } interface PerModuleNameCache { - get(directory: string): ResolvedModuleWithFailedLookupLocations; + get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; @@ -3570,7 +3581,7 @@ declare namespace ts { function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; function createTypeQueryNode(exprName: EntityName): TypeQueryNode; function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createTypeLiteralNode(members: ReadonlyArray): TypeLiteralNode; + function createTypeLiteralNode(members: ReadonlyArray | undefined): TypeLiteralNode; function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; @@ -3609,23 +3620,23 @@ declare namespace ts { function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; - function createPropertyAccess(expression: Expression, name: string | Identifier): PropertyAccessExpression; + function createPropertyAccess(expression: Expression, name: string | Identifier | undefined): PropertyAccessExpression; function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; - function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): CallExpression; function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; - function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray, template: TemplateLiteral): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; - function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray, template: TemplateLiteral): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; function createParen(expression: Expression): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; @@ -3655,15 +3666,15 @@ declare namespace ts { function createTemplateTail(text: string): TemplateTail; function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; function createYield(expression?: Expression): YieldExpression; - function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; + function createYield(asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function createSpread(expression: Expression): SpreadElement; function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; - function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; - function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; function createOmittedExpression(): OmittedExpression; - function createExpressionWithTypeArguments(typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; - function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; function createAsExpression(expression: Expression, type: TypeNode): AsExpression; function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; @@ -3690,8 +3701,8 @@ declare namespace ts { function updateFor(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - function createForOf(awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; - function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createForOf(awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; function createContinue(label?: string | Identifier): ContinueStatement; function updateContinue(node: ContinueStatement, label: Identifier | undefined): ContinueStatement; function createBreak(label?: string | Identifier): BreakStatement; @@ -3715,8 +3726,8 @@ declare namespace ts { function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; - function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; @@ -3734,7 +3745,7 @@ declare namespace ts { function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; - function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function createNamespaceImport(name: Identifier): NamespaceImport; @@ -3743,7 +3754,7 @@ declare namespace ts { function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; @@ -3873,16 +3884,16 @@ declare namespace ts { */ function setCommentRange(node: T, range: TextRange): T; function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[]): T; + function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T; function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; + function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; function moveSyntheticComments(node: T, original: Node): T; /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number | undefined; /** * Sets the constant value to emit for an expression. */ @@ -3918,7 +3929,7 @@ declare namespace ts { * @param test A callback to execute to verify the Node is valid. * @param lift An optional callback to execute to lift a NodeArray into a valid Node. */ - function visitNode(node: T, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; /** * Visits a Node using the supplied visitor, possibly returning a new Node in its place. * @@ -3927,7 +3938,7 @@ declare namespace ts { * @param test A callback to execute to verify the Node is valid. * @param lift An optional callback to execute to lift a NodeArray into a valid Node. */ - function visitNode(node: T | undefined, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; /** * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. * @@ -3937,7 +3948,7 @@ declare namespace ts { * @param start An optional value indicating the starting offset at which to start visiting. * @param count An optional value indicating the maximum number of nodes to visit. */ - function visitNodes(nodes: NodeArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; /** * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. * @@ -3957,7 +3968,7 @@ declare namespace ts { * Starts a new lexical environment and visits a parameter list, suspending the lexical * environment upon completion. */ - function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; /** * Resumes a suspended lexical environment and visits a function body, ending the lexical * environment and merging hoisted declarations upon completion. @@ -4006,7 +4017,7 @@ declare namespace ts { function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string; function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' @@ -4201,11 +4212,11 @@ declare namespace ts { /** If provided would be used to write log about compilation */ trace?(s: string): void; /** If provided is used to get the environment variable */ - getEnvironmentVariable?(name: string): string; + getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; /** Used to watch changes in source files, missing files needed to update the program or config file */ watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ @@ -4355,8 +4366,8 @@ declare namespace ts { getLeadingTriviaWidth(sourceFile?: SourceFile): number; getFullText(sourceFile?: SourceFile): string; getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node; - getLastToken(sourceFile?: SourceFile): Node; + getFirstToken(sourceFile?: SourceFile): Node | undefined; + getLastToken(sourceFile?: SourceFile): Node | undefined; forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; } interface Identifier { @@ -4444,7 +4455,7 @@ declare namespace ts { referencedFiles: FileReference[]; typeReferenceDirectives: FileReference[]; importedFiles: FileReference[]; - ambientExternalModules: string[]; + ambientExternalModules?: string[]; isLibFile: boolean; } interface HostCancellationToken { @@ -4477,7 +4488,7 @@ declare namespace ts { fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; - getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getDirectories?(directoryName: string): string[]; /** @@ -4497,9 +4508,10 @@ declare namespace ts { } interface LanguageService { cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(fileName: string): Diagnostic[]; - getSuggestionDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. @@ -4511,24 +4523,24 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails; - getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol; - getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; - getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; + getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; - getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - findReferences(fileName: string, position: number): ReferencedSymbol[]; - getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; @@ -4539,9 +4551,9 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan | undefined; toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; @@ -4559,7 +4571,7 @@ declare namespace ts { organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; - getProgram(): Program; + getProgram(): Program | undefined; dispose(): void; } interface CombinedCodeFixScope { @@ -4662,7 +4674,7 @@ declare namespace ts { } interface CombinedCodeActions { changes: ReadonlyArray; - commands: ReadonlyArray | undefined; + commands?: ReadonlyArray; } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { @@ -4712,8 +4724,8 @@ declare namespace ts { */ interface RefactorEditInfo { edits: FileTextChanges[]; - renameFilename: string | undefined; - renameLocation: number | undefined; + renameFilename?: string; + renameLocation?: number; commands?: CodeActionCommand[]; } interface TextInsertion { @@ -4834,7 +4846,7 @@ declare namespace ts { containerName: string; } interface DefinitionInfoAndBoundSpan { - definitions: ReadonlyArray; + definitions?: ReadonlyArray; textSpan: TextSpan; } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { @@ -4880,13 +4892,13 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; textSpan: TextSpan; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - tags: JSDocTagInfo[]; + displayParts?: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; } interface RenameInfo { canRename: boolean; - localizedErrorMessage: string; + localizedErrorMessage?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; @@ -4938,7 +4950,7 @@ declare namespace ts { interface CompletionEntry { name: string; kind: ScriptElementKind; - kindModifiers: string; + kindModifiers?: string; sortText: string; insertText?: string; /** @@ -4956,8 +4968,8 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - tags: JSDocTagInfo[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; source?: SymbolDisplayPart[]; } @@ -5270,12 +5282,12 @@ declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string; function getDefaultCompilerOptions(): CompilerOptions; function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; - function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnly?: boolean): LanguageService; /** * Get the path of the default library files (lib.d.ts) as distributed with the typescript diff --git a/lib/typescript.js b/lib/typescript.js index 5a20323ef59..01ebe51383d 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1325,6 +1325,7 @@ var ts; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; @@ -1633,7 +1634,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "2.9"; + ts.versionMajorMinor = "3.0"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1937,7 +1938,7 @@ var ts; return result; } } - Debug.fail(); + return Debug.fail(); } ts.findMap = findMap; function contains(array, value, equalityComparer) { @@ -2055,11 +2056,6 @@ var ts; return array; } ts.sameMap = sameMap; - /** - * Flattens an array containing a mix of array or non-array elements. - * - * @param array The array to flatten. - */ function flatten(array) { var result; if (array) { @@ -2079,12 +2075,6 @@ var ts; return result; } ts.flatten = flatten; - /** - * Maps an array. If the mapped value is an array, it is spread into the result. - * - * @param array The array to map. - * @param mapfn The callback used to map the result into one or more values. - */ function flatMap(array, mapfn) { var result; if (array) { @@ -2207,13 +2197,6 @@ var ts; }; } ts.singleIterator = singleIterator; - /** - * Maps contiguous spans of values with the same key. - * - * @param array The array to map. - * @param keyfn A callback used to select the key for an element. - * @param mapfn A callback used to map a contiguous chunk of values to a single value. - */ function spanMap(array, keyfn, mapfn) { var result; if (array) { @@ -2331,12 +2314,6 @@ var ts; } return result; } - /** - * Deduplicates an unsorted array. - * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. - * @param comparer An optional `Comparer` used to sort entries before comparison, though the - * result will remain in the original order in `array`. - */ function deduplicate(array, equalityComparer, comparer) { return !array ? undefined : array.length === 0 ? [] : @@ -2345,9 +2322,6 @@ var ts; deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; - /** - * Deduplicates an array that has already been sorted. - */ function deduplicateSorted(array, comparer) { if (!array) return undefined; @@ -2490,14 +2464,6 @@ var ts; return result; } ts.sum = sum; - /** - * Appends a value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param value The value to append to the array. If `value` is `undefined`, nothing is - * appended. - */ function append(to, value) { if (value === undefined) return to; @@ -2514,16 +2480,6 @@ var ts; function toOffset(array, offset) { return offset < 0 ? array.length + offset : offset; } - /** - * Appends a range of value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - * @param start The offset in `from` at which to start copying values. - * @param end The offset in `from` at which to stop copying values (non-inclusive). - */ function addRange(to, from, start, end) { if (from === undefined || from.length === 0) return to; @@ -2539,23 +2495,6 @@ var ts; return to; } ts.addRange = addRange; - /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - */ - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; /** * @return Whether the value was added. */ @@ -2853,7 +2792,7 @@ var ts; var arg = args_1[_a]; for (var p in arg) { if (hasProperty(arg, p)) { - t[p] = arg[p]; + t[p] = arg[p]; // TODO: GH#23368 } } } @@ -3012,10 +2951,10 @@ var ts; if (value !== undefined && test(value)) return value; if (value && typeof value.kind === "number") { - Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); } else { - Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } } ts.cast = cast; @@ -3101,7 +3040,7 @@ var ts; } ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { - baseIndex = baseIndex || 0; + if (baseIndex === void 0) { baseIndex = 0; } return text.replace(/{(\d+)}/g, function (_match, index) { return Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; @@ -3409,7 +3348,9 @@ var ts; return compareValues(a ? 1 : 0, b ? 1 : 0); } ts.compareBooleans = compareBooleans; - function compareMessageText(text1, text2) { + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; while (text1 && text2) { // We still have both chains. var string1 = isString(text1) ? text1 : text1.messageText; @@ -3446,6 +3387,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -3464,7 +3413,7 @@ var ts; } ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { - return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { @@ -3989,7 +3938,7 @@ var ts; /** * Matches any single directory segment unless it is the last segment and a .min.js file * Breakdown: - * [^./] # matches everything up to the first . character (excluding directory seperators) + * [^./] # matches everything up to the first . character (excluding directory separators) * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension */ singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", @@ -4051,7 +4000,7 @@ var ts; var subpattern = ""; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); - var lastComponent = lastOrUndefined(components); + var lastComponent = last(components); if (usage !== "exclude" && lastComponent === "**") { return undefined; } @@ -4277,11 +4226,11 @@ var ts; return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { @@ -4487,7 +4436,8 @@ var ts; } Debug.fail = fail; function assertDefined(value, message) { - assert(value !== undefined && value !== null, message); + if (value === undefined || value === null) + return fail(message); return value; } Debug.assertDefined = assertDefined; @@ -4671,10 +4621,7 @@ var ts; */ function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); - if (ext !== undefined) { - return ext; - } - Debug.fail("File " + path + " has unknown extension."); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; function isAnySupportedFileExtension(path) { @@ -5118,6 +5065,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: this is used as if it's certainly defined in many places. ts.sys = (function () { // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual // byte order mark from the specified encoding. Using any other byte order mark does @@ -5299,6 +5247,7 @@ var ts; return watchDirectoryRecursively(directoryName, callback); } watchDirectory(directoryName, callback); + return undefined; // TODO: GH#18217 }; } function createNonPollingWatchFile() { @@ -5330,7 +5279,7 @@ var ts; var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" var fileName = !ts.isString(relativeFileName) - ? undefined + ? undefined // TODO: GH#18217 : ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); @@ -5579,6 +5528,7 @@ var ts; switch (entryKind) { case 0 /* File */: return stat.isFile(); case 1 /* Directory */: return stat.isDirectory(); + default: return false; } } catch (e) { @@ -6274,7 +6224,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -6602,6 +6552,8 @@ var ts; _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Enable_strict_checking_of_any_type: diag(6200, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_any_type_6200", "Enable strict checking of 'any' type."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -6629,7 +6581,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -6710,6 +6662,7 @@ var ts; Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -6779,6 +6732,7 @@ var ts; Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), }; })(ts || (ts = {})); var ts; @@ -7485,8 +7439,9 @@ var ts; } ts.isIdentifierText = isIdentifierText; // Creates a scanner over a (possibly unspecified) range of a piece of text. - function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; // Current position (end position of text of current token) var pos; // end of text @@ -7942,7 +7897,7 @@ var ts; var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); - // Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator if (ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (separatorAllowed) { @@ -8758,7 +8713,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function packageIdToString(_a) { var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; @@ -8896,6 +8851,27 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Appends a range of value to begin of an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; /** * Determine if the given comment is a triple-slash * @@ -8985,7 +8961,7 @@ var ts; */ function getEmitFlags(node) { var emitNode = node.emitNode; - return emitNode && emitNode.flags; + return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { @@ -9019,7 +8995,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return node.text; } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { @@ -9127,7 +9103,7 @@ var ts; case 212 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block - return parentNode && !ts.isFunctionLike(parentNode); + return !ts.isFunctionLike(parentNode); } return false; } @@ -9219,7 +9195,7 @@ var ts; case 8 /* NumericLiteral */: return escapeLeadingUnderscores(name.text); case 146 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; + return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: ts.Debug.assertNever(name); } @@ -9233,6 +9209,8 @@ var ts; return entityNameToString(name.left) + "." + entityNameToString(name.right); case 184 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); } } ts.entityNameToString = entityNameToString; @@ -9441,7 +9419,7 @@ var ts; // falls through case 145 /* QualifiedName */: case 184 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: + case 99 /* ThisKeyword */: { var parent = node.parent; if (parent.kind === 164 /* TypeQuery */) { return false; @@ -9490,6 +9468,7 @@ var ts; // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } + } } return false; } @@ -9685,15 +9664,16 @@ var ts; return ts.filter(objectLiteral.properties, function (property) { if (property.kind === 269 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); - return key === propName || (key2 && key2 === propName); + return key === propName || (!!key2 && key2 === propName); } + return false; }); } ts.getPropertyAssignment = getPropertyAssignment; function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { var expression = tsConfigSourceFile.statements[0].expression; - return ts.isObjectLiteralExpression(expression) && expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); } } ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; @@ -9716,10 +9696,11 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 273 /* SourceFile */); while (true) { node = node.parent; if (!node) { - return undefined; + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { case 146 /* ComputedPropertyName */: @@ -9924,20 +9905,22 @@ var ts; ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node, parent, grandparent); + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; function nodeOrChildIsDecorated(node, parent, grandparent) { - return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { case 234 /* ClassDeclaration */: - return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 case 153 /* MethodDeclaration */: case 156 /* SetAccessor */: - return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; } } ts.childIsDecorated = childIsDecorated; @@ -10081,15 +10064,15 @@ var ts; } ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536 /* JavaScriptFile */); + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; function isInJsonFile(node) { - return node && !!(node.flags & 16777216 /* JsonFile */); + return !!node && !!(node.flags & 16777216 /* JsonFile */); } ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { - return node && !!(node.flags & 2097152 /* JSDoc */); + return !!node && !!(node.flags & 2097152 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; function isJSDocIndexSignature(node) { @@ -10360,7 +10343,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 243 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 243 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { @@ -10397,16 +10380,18 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ && - node.expression.right; + node.expression.operatorToken.kind === 58 /* EqualsToken */ + ? node.expression.right + : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ && - node.expression.right.right; + node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + ? node.expression.right.right + : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { @@ -10420,15 +10405,14 @@ var ts; } } function getSingleVariableOfVariableStatement(node) { - return ts.isVariableStatement(node) && - node.declarationList.declarations.length > 0 && - node.declarationList.declarations[0]; + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } function getNestedModuleDeclaration(node) { - return node.kind === 238 /* ModuleDeclaration */ && + return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 238 /* ModuleDeclaration */ && - node.body; + node.body.kind === 238 /* ModuleDeclaration */ + ? node.body + : undefined; } function getJSDocCommentsAndTags(hostNode) { var result; @@ -10517,12 +10501,12 @@ var ts; ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { var last = ts.lastOrUndefined(s.parameters); - return last && isRestParameter(last); + return !!last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || type && type.kind === 284 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 284 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -10660,9 +10644,10 @@ var ts; switch (name.kind) { case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - if (ts.isDeclaration(name.parent)) { - return name.parent.name === name; + case 8 /* NumericLiteral */: { + var parent = name.parent; + if (ts.isDeclaration(parent)) { + return parent.name === name; } else if (ts.isQualifiedName(name.parent)) { var tag = name.parent.parent; @@ -10672,6 +10657,7 @@ var ts; var binExp = name.parent.parent; return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; } + } default: return false; } @@ -10876,7 +10862,7 @@ var ts; */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); - return name && isDynamicName(name); + return !!name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -11169,7 +11155,7 @@ var ts; } ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; function createDiagnosticCollection() { - var nonFileDiagnostics = []; + var nonFileDiagnostics = []; // See GH#19873 var filesWithDiagnostics = []; var fileDiagnostics = ts.createMap(); var hasReadNonFileDiagnostics = false; @@ -11187,7 +11173,7 @@ var ts; if (diagnostic.file) { diagnostics = fileDiagnostics.get(diagnostic.file.fileName); if (!diagnostics) { - diagnostics = []; + diagnostics = []; // See GH#19873 fileDiagnostics.set(diagnostic.file.fileName, diagnostics); ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); } @@ -11334,7 +11320,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); + linePos = output.length - s.length + ts.last(lineStartsOfS); } } } @@ -11509,7 +11495,7 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { @@ -11517,6 +11503,7 @@ var ts; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 var firstAccessor; var secondAccessor; var getAccessor; @@ -11713,13 +11700,13 @@ var ts; // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; } } } @@ -11888,7 +11875,7 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 206 /* ExpressionWithTypeArguments */ && + if (ts.isExpressionWithTypeArguments(node) && node.parent.token === 85 /* ExtendsKeyword */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -12858,7 +12845,7 @@ var ts; // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) ts.localizedDiagnosticMessages = JSON.parse(fileContents); } - catch (e) { + catch (_a) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); } @@ -12987,6 +12974,7 @@ var ts; return !!node.name; // A 'name' property should always be a DeclarationName. } ts.isNamedDeclaration = isNamedDeclaration; + // TODO: GH#18217 This is often used as if it returns a defined result function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -13912,7 +13900,6 @@ var ts; // Identifiers /* @internal */ function isGeneratedIdentifier(node) { - // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; @@ -14610,8 +14597,10 @@ var ts; ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times function hasJSDocNodes(node) { - return !!node.jsDoc && node.jsDoc.length > 0; + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; /** True if has type node attached to it. */ @@ -15278,6 +15267,7 @@ var ts; // becoming detached from any SourceFile). It is recommended that this SourceFile not // be used once 'update' is called on it. function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. // We will manually port the flag to the new source file. @@ -15403,6 +15393,7 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); @@ -15604,6 +15595,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -16124,7 +16116,7 @@ var ts; case 14 /* JsxChildren */: return true; } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); @@ -16213,6 +16205,8 @@ var ts; return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; case 14 /* JsxChildren */: return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; } } function isVariableDeclaratorListTerminator() { @@ -16544,6 +16538,7 @@ var ts; case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; + default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` } } // Parses a comma-delimited list of elements @@ -16676,7 +16671,7 @@ var ts; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } @@ -16915,7 +16910,7 @@ var ts; if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); + signature.parameters = parseParameterList(flags); // TODO: GH#18217 if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { signature.type = parseTypeOrTypePredicate(); return signature.type !== undefined; @@ -17077,7 +17072,7 @@ var ts; if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return true; } - var idToken; + var idToken = false; // Eat up all modifiers, but hold on to the last one in case it is actually an identifier while (ts.isModifierKind(token())) { idToken = true; @@ -17200,7 +17195,7 @@ var ts; parseExpected(19 /* OpenParenToken */); node.type = parseType(); if (!node.type) { - return undefined; + return undefined; // TODO: GH#18217 } parseExpected(20 /* CloseParenToken */); return finishNode(node); @@ -17532,7 +17527,7 @@ var ts; } function parseTypeWorker(noConditionalTypes) { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162 /* FunctionType */); + return parseFunctionOrConstructorType(162 /* FunctionType */); // TODO: GH#18217 } if (token() === 94 /* NewKeyword */) { return parseFunctionOrConstructorType(163 /* ConstructorType */); @@ -18499,7 +18494,7 @@ var ts; badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -19554,6 +19549,7 @@ var ts; missing.modifiers = node.modifiers; return finishNode(missing); } + return undefined; // TODO: GH#18217 } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { @@ -19897,7 +19893,7 @@ var ts; return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. - ts.Debug.fail("Should not have attempted to parse class member declaration."); + return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 204 /* ClassExpression */); @@ -19945,14 +19941,12 @@ var ts; } function parseHeritageClause() { var tok = token(); - if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { - var node = createNode(267 /* HeritageClause */); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; + ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(267 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); } function parseExpressionWithTypeArguments() { var node = createNode(206 /* ExpressionWithTypeArguments */); @@ -20384,8 +20378,8 @@ var ts; PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } var content = sourceText; - start = start || 0; var end = length === undefined ? content.length : start + length; length = end - start; ts.Debug.assert(start >= 0); @@ -20715,7 +20709,7 @@ var ts; var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -20795,7 +20789,7 @@ var ts; while (parseOptional(23 /* DotToken */)) { var prop = createNode(184 /* PropertyAccessExpression */, node.pos); prop.expression = node; - prop.name = parseJSDocIdentifierName(); + prop.name = parseJSDocIdentifierName(); // TODO: GH#18217 node = finishNode(prop); } return node; @@ -20935,7 +20929,7 @@ var ts; var child = tryParseChildTag(target); if (child && child.kind === 292 /* JSDocParameterTag */ && target !== 4 /* CallbackParameter */ && - (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { // TODO: GH#18217 return false; } return child; @@ -21581,7 +21575,7 @@ var ts; context.pragmas = ts.createMap(); for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { var pragma = pragmas_1[_i]; - if (context.pragmas.has(pragma.name)) { + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 var currentValue = context.pragmas.get(pragma.name); if (currentValue instanceof Array) { currentValue.push(pragma.args); @@ -21610,6 +21604,7 @@ var ts; var referencedFiles_1 = context.referencedFiles; var typeReferenceDirectives_1 = context.typeReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } @@ -21626,10 +21621,7 @@ var ts; break; } case "amd-dependency": { - context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { - var _b = _a.arguments, name = _b.name, path = _b.path; - return ({ name: name, path: path }); - }); + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 break; } case "amd-module": { @@ -21652,7 +21644,7 @@ var ts; case "ts-check": { // _last_ of either nocheck or check in a file is the "winner" ts.forEach(ts.toArray(entryOrList), function (entry) { - if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 context.checkJsDirective = { enabled: key === "ts-check", end: entry.range.end, @@ -22036,7 +22028,7 @@ var ts; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); // TODO: GH#18217 } /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @@ -22836,6 +22828,7 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -22877,7 +22870,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -23261,7 +23254,7 @@ var ts; // We do that by making an anonymous type literal symbol, and then setting the function // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. - var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 addDeclarationToSymbol(symbol, node, 131072 /* Signature */); var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); @@ -23507,6 +23500,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -24036,7 +24039,7 @@ var ts; (symbol.exports || (symbol.exports = ts.createSymbolTable())); // Declare the method/property var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); // TODO: GH#18217 var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); @@ -24066,7 +24069,8 @@ var ts; } else { var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); - ts.Debug.assert(!!s && !!s.exports); + if (!s || !s.exports) + return ts.Debug.fail(); return action(e.name, s.exports.get(e.name.escapedText)); } } @@ -24207,7 +24211,7 @@ var ts; } function bindTypeParameter(node) { if (ts.isJSDocTemplateTag(node.parent)) { - var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 if (container_1) { if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); @@ -24227,7 +24231,7 @@ var ts; declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } else { - bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { @@ -24237,7 +24241,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -24255,22 +24259,22 @@ var ts; (node.kind === 237 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304 /* Ambient */) && - (node.kind !== 213 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -24286,8 +24290,8 @@ var ts; ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { return isExportsOrModuleExportsOrAlias(sourceFile, node) || @@ -25282,11 +25286,11 @@ var ts; } function visitSymbol(symbol) { if (!symbol) { - return; + return false; } var symbolId = ts.getSymbolId(symbol); if (visitedSymbols[symbolId]) { - return; + return false; } visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { @@ -25308,6 +25312,7 @@ var ts; visitSymbol(entity); } }); + return false; } } } @@ -25321,7 +25326,7 @@ var ts; ts.trace = trace; /* @internal */ function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; + return !!compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; function withPackageId(packageId, r) { @@ -25501,7 +25506,6 @@ var ts; } } function secondaryLookup() { - var resolvedFile; var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations @@ -25509,7 +25513,7 @@ var ts; trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); + var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -25582,7 +25586,7 @@ var ts; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; + return undefined; // TODO: GH#18217 } var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { @@ -25694,7 +25698,7 @@ var ts; result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; default: - ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -25947,7 +25951,7 @@ var ts; var originalPath = void 0; if (!compilerOptions.preserveSymlinks && resolvedValue) { originalPath = resolvedValue.path; - var path = realPath(resolved_1.value.path, host, traceEnabled); + var path = realPath(resolvedValue.path, host, traceEnabled); if (path === originalPath) { originalPath = undefined; } @@ -26066,7 +26070,7 @@ var ts; function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); @@ -26105,7 +26109,7 @@ var ts; } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, ext: ext }; + return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ @@ -26495,6 +26499,7 @@ var ts; var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var strictAny = ts.getStrictOptionValue(compilerOptions, "strictAny"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; @@ -26527,9 +26532,10 @@ var ts; location = ts.getParseTreeNode(location); return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); }, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, @@ -26541,8 +26547,8 @@ var ts; getBaseTypes: getBaseTypes, getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node ? getTypeFromTypeNode(node) : unknownType; }, getParameterType: getTypeAtPosition, @@ -26569,8 +26575,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getShorthandAssignmentValueSymbol(node) : undefined; }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, getExportSymbolOfSymbol: function (symbol) { @@ -26580,8 +26586,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; }, signatureToString: function (signature, enclosingDeclaration, flags, kind) { @@ -26611,41 +26617,41 @@ var ts; getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, - getContextualTypeForArgumentAtIndex: function (node, argIndex) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); }, - getContextualTypeForJsxAttribute: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxAttributeLike); + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); apparentArgumentCount = theArgumentCount; var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; apparentArgumentCount = undefined; return res; }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); }, - isValidPropertyAccessForCompletions: function (node, type, property) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); return !!node && isValidPropertyAccessForCompletions(node, type, property); }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); return declaration ? getSignatureFromDeclaration(declaration) : undefined; }, isImplementationOfOverload: function (node) { @@ -26657,7 +26663,8 @@ var ts; var links = getSymbolLinks(symbol); if (!links.immediateTarget) { var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); } return links.immediateTarget; @@ -26668,13 +26675,13 @@ var ts; getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); return node ? isOptionalParameter(node) : false; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, @@ -26720,8 +26727,8 @@ var ts; node = ts.getParseTreeNode(node); return node && tryGetThisTypeAt(node); }, - getTypeArgumentConstraint: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file) { @@ -27028,6 +27035,7 @@ var ts; typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); }, buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); }, buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { @@ -27041,12 +27049,12 @@ var ts; buildParameterDisplay: function (symbol, writer, enclosing, flags) { var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 }, buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 }, buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); @@ -27059,13 +27067,13 @@ var ts; buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { var printer = ts.createPrinter({ removeComments: true }); var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); - var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; - var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; // TODO: GH#18217 + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); // TODO: GH#18217 printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); }, buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { var printer = ts.createPrinter({ removeComments: true }); - var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); // TODO: GH#18217 printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); }, buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { @@ -27077,7 +27085,7 @@ var ts; } var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 } }; function emitTextWriterWrapper(underlying) { @@ -27164,7 +27172,7 @@ var ts; } var jsxPragma = file_1.pragmas.get("jsx"); if (jsxPragma) { - var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file_1.localJsxFactory) { return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText; @@ -27459,7 +27467,7 @@ var ts; if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); @@ -27534,7 +27542,8 @@ var ts; break; } // ForIn/ForOf case - use site should not be used in expression part - return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); } function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { return !!ts.findAncestor(usage, function (current) { @@ -27560,6 +27569,7 @@ var ts; } } } + return false; }); } } @@ -27838,7 +27848,7 @@ var ts; if (!result) { if (nameNotFoundMessage) { if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && @@ -27890,7 +27900,7 @@ var ts; if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 241 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } } @@ -27918,7 +27928,7 @@ var ts; if (decl.kind === 147 /* TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 } } } @@ -27945,7 +27955,7 @@ var ts; // No static member is present. // Check if we're in an instance method and look for a relevant instance member. if (location === container && !ts.hasModifier(location, 32 /* Static */)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); return true; @@ -27958,11 +27968,11 @@ var ts; } function checkAndReportErrorForExtendingInterface(errorLocation) { var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); - if (isError) { + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; + return false; } /** * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, @@ -28038,7 +28048,8 @@ var ts; ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 237 /* EnumDeclaration */) ? d : undefined; }); - ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); @@ -28056,7 +28067,7 @@ var ts; * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. */ function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { switch (node.kind) { @@ -28191,12 +28202,13 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 } } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { var name = specifier.propertyName || specifier.name; @@ -28261,6 +28273,7 @@ var ts; return getNodeLinks(expression).resolvedSymbol; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { case 242 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); @@ -28277,6 +28290,8 @@ var ts; return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 241 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); } } /** @@ -28287,11 +28302,10 @@ var ts; if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || (symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); } function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); - return shouldResolve ? resolveAlias(symbol) : symbol; + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); @@ -28299,7 +28313,8 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -28332,7 +28347,8 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); if (node.kind === 248 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); @@ -28431,7 +28447,7 @@ var ts; } } else { - ts.Debug.assertNever(name, "Unknown entity name kind."); + throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -28492,7 +28508,7 @@ var ts; return ambientModule; } var currentSourceFile = ts.getSourceFileOfNode(location); - var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -28566,8 +28582,6 @@ var ts; /*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)); errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } - // 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) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } @@ -28899,7 +28913,7 @@ var ts; // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -28927,6 +28941,11 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } @@ -28934,7 +28953,7 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; @@ -29008,7 +29027,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // Any meaning of a module symbol is always accessible via an `import` type return { accessibility: 0 /* Accessible */ @@ -29059,6 +29078,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -29144,7 +29166,7 @@ var ts; var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { - var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); @@ -29152,6 +29174,7 @@ var ts; } } function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); function signatureToStringWorker(writer) { var sigOutput; @@ -29164,15 +29187,16 @@ var ts; var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 return writer; } } function typeToString(type, enclosingDeclaration, flags, writer) { - if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; } + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } 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"); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); @@ -29185,6 +29209,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } return flags & 9469291 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { @@ -29201,7 +29226,7 @@ var ts; var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; - return result; + return result; // TODO: GH#18217 }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); @@ -29249,7 +29274,7 @@ var ts; function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, - flags: flags, + flags: flags || 0 /* None */, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, @@ -29264,7 +29289,7 @@ var ts; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { return ts.createKeywordTypeNode(119 /* AnyKeyword */); @@ -29354,9 +29379,10 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); @@ -29375,7 +29401,7 @@ var ts; if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } - return undefined; + return undefined; // TODO: GH#18217 } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { @@ -29406,7 +29432,7 @@ var ts; if (type.flags & 4194304 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } - ts.Debug.fail("Should be unreachable."); + return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -29480,7 +29506,7 @@ var ts; if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively - (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } } @@ -29532,7 +29558,7 @@ var ts; return ts.createTupleTypeNode([]); } context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && @@ -29655,7 +29681,7 @@ var ts; var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(propertySymbol.declarations); + var decl = ts.first(propertySymbol.declarations); var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); if (name && context.tracker.trackSymbol) { context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); @@ -29718,7 +29744,7 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } @@ -29795,7 +29821,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration @@ -29823,12 +29849,12 @@ var ts; } } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { - context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { - chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } else { @@ -29858,7 +29884,7 @@ var ts; // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; @@ -30035,6 +30061,7 @@ var ts; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); @@ -30115,7 +30142,7 @@ var ts; return "default"; } if (symbol.declarations && symbol.declarations.length) { - if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { + if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { // TODO: GH#18217 var file_3 = ts.getDeclarationOfKind(symbol, 273 /* SourceFile */); if (!file_3 || !context.tracker.moduleResolverHost) { if (context.tracker.trackReferencedAmbientModule) { @@ -30123,7 +30150,7 @@ var ts; if (ts.length(ambientDecls)) { for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { var decl = ambientDecls_1[_i]; - context.tracker.trackReferencedAmbientModule(decl); + context.tracker.trackReferencedAmbientModule(decl); // TODO: GH#18217 } } } @@ -30329,22 +30356,22 @@ var ts; } function hasType(target, propertyName) { if (propertyName === 0 /* Type */) { - return getSymbolLinks(target).type; + return !!getSymbolLinks(target).type; } if (propertyName === 2 /* DeclaredType */) { - return getSymbolLinks(target).declaredType; + return !!getSymbolLinks(target).declaredType; } if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return target.resolvedBaseConstructorType; + return !!target.resolvedBaseConstructorType; } if (propertyName === 3 /* ResolvedReturnType */) { - return target.resolvedReturnType; + return !!target.resolvedReturnType; } if (propertyName === 4 /* ResolvedBaseConstraint */) { var bc = target.resolvedBaseConstraint; - return bc && bc !== circularConstraintType; + return !!bc && bc !== circularConstraintType; } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -30354,7 +30381,7 @@ var ts; return resolutionResults.pop(); } function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { case 231 /* VariableDeclaration */: case 232 /* VariableDeclarationList */: @@ -30366,8 +30393,7 @@ var ts; default: return true; } - }); - return node && node.parent; + }).parent; } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 @@ -30480,7 +30506,7 @@ var ts; } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - var nameType = isLate && checkComputedPropertyName(name); + var nameType = isLate ? checkComputedPropertyName(name) : undefined; var text = isLate ? getLateBoundNameFromType(nameType) : isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : ts.getTextOfPropertyName(name); @@ -30742,7 +30768,7 @@ var ts; definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 /* Nullable */ | 16777216 /* ContainsWideningType */)); }) ? constructorTypes : types; + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 /* Nullable */ | 16777216 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); @@ -30818,7 +30844,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + if (!lastElement || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. @@ -30838,6 +30864,8 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } return pattern.kind === 179 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); @@ -30956,7 +30984,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } else { - ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); } if (!popTypeResolution()) { type = reportCircularityError(symbol); @@ -31158,16 +31186,18 @@ var ts; function getTargetType(type) { return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. function hasBaseType(type, checkBase) { return check(type); function check(type) { if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); + return target === checkBase || ts.some(getBaseTypes(target), check); } else if (type.flags & 262144 /* Intersection */) { - return ts.forEach(type.types, check); + return ts.some(type.types, check); } + return false; } } // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. @@ -31183,7 +31213,7 @@ var ts; // Return the outer type parameters of a node or undefined if the node has no outer type parameters. function getOuterTypeParameters(node, includeThisTypes) { while (true) { - node = node.parent; + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead if (!node) { return undefined; } @@ -31264,7 +31294,7 @@ var ts; } if (type.flags & 1081344 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } @@ -31396,7 +31426,7 @@ var ts; // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a // partial instantiation of the members without the base types fully resolved - type.members = undefined; + type.members = undefined; // TODO: GH#18217 } return type.resolvedBaseTypes = [baseType]; } @@ -31414,8 +31444,8 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return type.flags & (65536 /* Object */ | 134217728 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || - type.flags & 262144 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return !!(type.flags & (65536 /* Object */ | 134217728 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 262144 /* Intersection */) && !ts.some(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -31605,7 +31635,7 @@ var ts; if (declaration.kind === 237 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; memberTypeList.push(memberType); } @@ -31720,7 +31750,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) && + return (node.kind === 154 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -31805,7 +31835,7 @@ var ts; */ function hasLateBindableName(node) { var name = ts.getNameOfDeclaration(node); - return name && isLateBindableName(name); + return !!name && isLateBindableName(name); } /** * Indicates whether a declaration has a dynamic name that cannot be late-bound. @@ -31829,6 +31859,7 @@ var ts; if (type.flags & 96 /* StringOrNumberLiteral */) { return ts.escapeLeadingUnderscores("" + type.value); } + return ts.Debug.fail(); } /** * Adds a declaration to a late-bound dynamic member. This performs the same function for @@ -31846,8 +31877,7 @@ var ts; symbol.declarations.push(member); } if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } } @@ -32075,7 +32105,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); @@ -32147,6 +32177,7 @@ var ts; if (unionSignatures.length > 1) { var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); thisParameter = createSymbolWithType(signature.thisParameter, thisType); } @@ -32412,7 +32443,7 @@ var ts; return type.declaration.typeParameter.constraint; } function isMappedTypeWithKeyofConstraintDeclaration(type) { - var constraintDeclaration = getConstraintDeclarationForMappedType(type); + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 return constraintDeclaration.kind === 174 /* TypeOperator */ && constraintDeclaration.operator === 128 /* KeyOfKeyword */; } @@ -32454,7 +32485,7 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); } function isGenericMappedType(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -33061,14 +33092,6 @@ var ts; } return minTypeArgumentCount; } - /** - * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined - * when a default type is supplied, a new array will be created and returned. - * - * @param typeArguments The supplied type arguments. - * @param typeParameters The requested type parameters. - * @param minTypeArgumentCount The minimum number of required type arguments. - */ function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { @@ -33103,7 +33126,7 @@ var ts; var hasLiteralTypes = false; var minArgumentCount = 0; var thisParameter = void 0; - var hasThisParameter = void 0; + var hasThisParameter = false; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && @@ -33190,7 +33213,7 @@ var ts; } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 } else if (classType) { return classType; @@ -33233,7 +33256,7 @@ var ts; return node.name.kind === 146 /* ComputedPropertyName */ && traverse(node.name); default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); } } } @@ -33243,7 +33266,7 @@ var ts; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { var decl = symbol.declarations[i]; - var node = ts.isPropertyAccessExpression(decl) ? ts.getAssignedJavascriptInitializer(decl) : decl; + var node = ts.isPropertyAccessExpression(decl) ? ts.getAssignedJavascriptInitializer(decl) : decl; // TODO: GH#18217 if (!ts.isFunctionLike(node)) continue; // Don't include signature if node is the implementation of an overloaded function. A node is considered @@ -33333,9 +33356,10 @@ var ts; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + var type = getTypeOfSymbol(ts.last(signature.parameters)); if (ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { - return type.typeArguments[0]; + var t = type.typeArguments[0]; + return strictAny && t.flags & 1 /* Any */ ? unknownType : t; } } return anyType; @@ -33394,7 +33418,7 @@ var ts; // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 154 /* Constructor */ || signature.declaration.kind === 158 /* ConstructSignature */; + var isConstructor = signature.declaration.kind === 154 /* Constructor */ || signature.declaration.kind === 158 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -33676,7 +33700,8 @@ var ts; var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); if (referenceType || assignedType) { - return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -33727,7 +33752,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return node.flags & 2097152 /* JSDoc */ && node.kind === 161 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 161 /* TypeReference */; } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -33774,7 +33799,7 @@ var ts; var indexed = getTypeFromTypeNode(typeArgs[0]); var target = getTypeFromTypeNode(typeArgs[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); } return anyType; } @@ -33911,7 +33936,7 @@ var ts; return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { - return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. @@ -34315,16 +34340,19 @@ var ts; // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); if (includes & 16384 /* Never */) { return neverType; } - if (includes & 1 /* Any */) { - return includes & 33554432 /* Wildcard */ ? wildcardType : anyType; + if (includes & 33554432 /* Wildcard */) { + return wildcardType; + } + if (!strictAny && includes & 1 /* Any */) { + return anyType; + } + if (!strictNullChecks && includes & 12288 /* Nullable */) { + return includes & 4096 /* Undefined */ ? undefinedType : nullType; } if (includes & 2 /* String */ && includes & 32 /* StringLiteral */ || includes & 4 /* Number */ && includes & 64 /* NumberLiteral */ || @@ -34334,6 +34362,9 @@ var ts; if (includes & 67108864 /* EmptyObject */ && !(includes & 65536 /* Object */)) { typeSet.push(emptyObjectType); } + if (typeSet.length === 0) { + return anyType; + } if (typeSet.length === 1) { return typeSet[0]; } @@ -34441,7 +34472,7 @@ var ts; break; } } - return links.resolvedType; + return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { var type = createType(1048576 /* IndexedAccess */); @@ -34530,12 +34561,12 @@ var ts; var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - t.stringIndexInfo && !t.numberIndexInfo; + !!t.stringIndexInfo && !t.numberIndexInfo; } return false; } function isMappedTypeToNever(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; } function getSimplifiedType(type) { return type.flags & 1048576 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; @@ -34720,7 +34751,7 @@ var ts; result.mapper = mapper; result.combinedMapper = combinedMapper; result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } function getTrueTypeFromConditionalType(type) { @@ -34849,7 +34880,7 @@ var ts; } } } - return links.resolvedType; + return links.resolvedType; // TODO: GH#18217 } function resolveImportSymbolType(node, links, symbol, meaning) { links.resolvedSymbol = symbol; @@ -35004,7 +35035,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -35138,7 +35171,7 @@ var ts; case 71 /* Identifier */: case 145 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 default: return unknownType; } @@ -35361,21 +35394,21 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_3; })) { - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { case 173 /* ThisType */: - return tp.isThisType; + return !!tp.isThisType; case 71 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; case 164 /* TypeQuery */: return true; } - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -35510,9 +35543,9 @@ var ts; case 153 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); case 183 /* ObjectLiteralExpression */: - return ts.forEach(node.properties, isContextSensitive); + return ts.some(node.properties, isContextSensitive); case 182 /* ArrayLiteralExpression */: - return ts.forEach(node.elements, isContextSensitive); + return ts.some(node.elements, isContextSensitive); case 200 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); @@ -35524,13 +35557,17 @@ var ts; case 190 /* ParenthesizedExpression */: return isContextSensitive(node.expression); case 262 /* JsxAttributes */: - return ts.forEach(node.properties, isContextSensitive); - case 261 /* JsxAttribute */: + return ts.some(node.properties, isContextSensitive); + case 261 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. - return node.initializer && isContextSensitive(node.initializer); - case 264 /* JsxExpression */: + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 264 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) - return node.expression && isContextSensitive(node.expression); + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } } return false; } @@ -35540,7 +35577,7 @@ var ts; return false; } // Functions with any parameters that lack type annotations are context sensitive. - if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } if (node.kind !== 192 /* ArrowFunction */) { @@ -35552,7 +35589,8 @@ var ts; } } // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return node.body.kind === 212 /* Block */ ? false : isContextSensitive(node.body); + var body = node.body; + return body.kind === 212 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -35692,6 +35730,7 @@ var ts; var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { @@ -35713,7 +35752,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -35805,8 +35844,8 @@ var ts; function isEmptyObjectType(type) { return type.flags & 65536 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 134217728 /* NonPrimitive */ ? true : - type.flags & 131072 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 262144 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + type.flags & 131072 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 262144 /* Intersection */ ? !ts.some(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -35881,7 +35920,7 @@ var ts; if (s & 1024 /* UniqueESSymbol */ || t & 1024 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { - if (s & 1 /* Any */) + if (s & 1 /* Any */ && (!strictAny || source === unknownType || t & 65536 /* Object */ && isEmptyObjectType(target))) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because @@ -35949,7 +35988,7 @@ var ts; errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); // TODO: GH#18217 } // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement if (headMessage && errorNode && !result && source.symbol) { @@ -36023,6 +36062,7 @@ var ts; * * Ternary.False if they are not related. */ function isRelatedTo(source, target, reportErrors, headMessage) { + if (reportErrors === void 0) { reportErrors = false; } if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 8388608 /* FreshLiteral */) { source = source.regularType; } @@ -36216,7 +36256,8 @@ var ts; // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. - ts.Debug.assert(!!errorNode); + if (!errorNode) + return { value: ts.Debug.fail() }; if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. @@ -36230,8 +36271,9 @@ var ts; var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; - if (ts.isIdentifier(propDeclaration.name)) { - suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); } } if (suggestion !== undefined) { @@ -36896,7 +36938,7 @@ var ts; // in the context of the target signature before checking the relationship. Ideally we'd do // this regardless of the number of signatures, but the potential costs are prohibitive due // to the quadratic nature of the logic below. - var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); } else { @@ -36992,7 +37034,7 @@ var ts; if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } // if T is related to U. - return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 } if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; @@ -37112,7 +37154,7 @@ var ts; return type.flags & 32768 /* TypeParameter */ && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -37366,7 +37408,7 @@ var ts; return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); } function isArrayType(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, @@ -37811,12 +37853,12 @@ var ts; } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); } return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 393216 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { @@ -38255,7 +38297,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); + return !!constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -38280,10 +38322,12 @@ var ts; // all inferences were made to top-level occurrences 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) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. @@ -38399,7 +38443,8 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 179 /* ObjectBindingPattern */) { + var parent = element.parent; + if (parent.kind === 179 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { case 71 /* Identifier */: @@ -38415,7 +38460,7 @@ var ts; } } else { - return "" + element.parent.elements.indexOf(element); + return "" + parent.elements.indexOf(element); } } function isMatchingReference(source, target) { @@ -38443,7 +38488,7 @@ var ts; } if (source.parent.parent.kind === 231 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; - return maybeId && isMatchingReference(maybeId, t.expression); + return !!maybeId && isMatchingReference(maybeId, t.expression); } } return false; @@ -38481,7 +38526,7 @@ var ts; var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -38807,9 +38852,6 @@ var ts; } return f(type) ? type : neverType; } - // Apply a mapping function to a type and return the resulting type. If the source type - // 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; @@ -39729,7 +39771,7 @@ var ts; // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container !== undefined) { + while (container.kind !== 273 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 151 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; @@ -40345,7 +40387,7 @@ var ts; if (funcHasRestParameters && indexOfParameter === (func.parameters.length - 1) && isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + return getTypeOfSymbol(ts.last(contextualSignature.parameters)); } } } @@ -40447,7 +40489,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); + var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -40501,7 +40543,7 @@ var ts; case 6 /* Prototype */: return false; default: - ts.Debug.assertNever(kind); + return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { @@ -40590,6 +40632,25 @@ var ts; return getContextualType(attribute.parent); } } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 71 /* Identifier */: + return true; + case 184 /* PropertyAccessExpression */: + case 190 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { @@ -40606,8 +40667,8 @@ var ts; continue; if (prop.kind !== 269 /* PropertyAssignment */) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -40703,8 +40764,8 @@ var ts; return undefined; } function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -41287,7 +41348,7 @@ var ts; case 71 /* Identifier */: return ts.isIntrinsicJsxName(tagName.escapedText); default: - ts.Debug.fail(); + return ts.Debug.fail(); } } function checkJsxAttribute(node, checkMode) { @@ -41501,6 +41562,7 @@ var ts; return instantiatedSignatures; } function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (reportErrors === void 0) { reportErrors = false; } if (!node.typeArguments) { return; } @@ -41523,7 +41585,7 @@ var ts; } } // JSX global fallback - return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -41639,6 +41701,7 @@ var ts; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); + // TODO: GH#18217: callReturnType should always be defined... var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { @@ -41647,7 +41710,7 @@ var ts; var attribute = _b[_a]; if (ts.isJsxAttribute(attribute) && isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { + !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 shouldBeCandidate = false; break; } @@ -41762,7 +41825,7 @@ var ts; if (!ts.length(instantiatedSignatures)) { return unknownType; } - var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -41776,7 +41839,7 @@ var ts; checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(ts.map(instantiatedSignatures, function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); + return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -42090,7 +42153,7 @@ var ts; if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } } @@ -42130,7 +42193,7 @@ var ts; } if (type.flags & 32768 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type - type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); @@ -42231,7 +42294,7 @@ var ts; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { - error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; } @@ -42489,7 +42552,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, left, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 131072 /* Union */) && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 131072 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -42646,7 +42709,7 @@ var ts; var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { - index++; + index = index + 1; } else { lastParent = parent; @@ -42689,7 +42752,7 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call var typeArguments; // Type arguments (undefined if none) - var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". @@ -42703,8 +42766,7 @@ var ts; if (node.template.kind === 201 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. - var lastSpan = ts.lastOrUndefined(node.template.templateSpans); - ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { @@ -42882,7 +42944,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -42939,7 +43001,7 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { return false; } } @@ -42991,7 +43053,7 @@ var ts; function getEffectiveCallArguments(node) { if (node.kind === 188 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; + var args_4 = [undefined]; // TODO: GH#18217 if (template.kind === 201 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -43052,6 +43114,8 @@ var ts; // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; + default: + return ts.Debug.fail(); } } else { @@ -43139,14 +43203,15 @@ var ts; // otherwise, if the member name is a computed property name it will // be either string or symbol. var element = node; - switch (element.name.kind) { + var name = element.name; + switch (name.kind) { case 71 /* Identifier */: - return getLiteralType(ts.idText(element.name)); + return getLiteralType(ts.idText(name)); case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralType(element.name.text); + return getLiteralType(name.text); case 146 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(element.name); + var nameType = checkComputedPropertyName(name); if (isTypeAssignableToKind(nameType, 1536 /* ESSymbolLike */)) { return nameType; } @@ -43188,7 +43253,7 @@ var ts; node.kind === 156 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - var propertyType = getTypeOfNode(node); + var propertyType = getTypeOfNode(node); // TODO: GH#18217 return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); @@ -43423,7 +43488,7 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); // TODO: GH#18217 while (typeArguments_1.length > typeParameters.length) { typeArguments_1.pop(); } @@ -43742,6 +43807,8 @@ var ts; case 155 /* GetAccessor */: case 156 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); } } /** @@ -43765,8 +43832,7 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); invocationErrorRecovery(apparentType, 0 /* Call */); @@ -43830,7 +43896,7 @@ var ts; return ts.length(sigs) ? sigs[0] : unknownSignature; }) || unknownSignature; } - ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } /** * Resolve a signature of a given call-like expression. @@ -43870,7 +43936,7 @@ var ts; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; - return symbol && symbol.members !== undefined; + return !!symbol && symbol.members !== undefined; } return false; } @@ -44053,7 +44119,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -44106,6 +44172,7 @@ var ts; if (node.keywordToken === 91 /* ImportKeyword */) { return checkImportMetaProperty(node); } + return ts.Debug.assertNever(node.keywordToken); } function checkNewTargetMetaProperty(node) { var container = ts.getNewTargetContainer(node); @@ -44185,9 +44252,9 @@ var ts; } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. - var parameter = ts.lastOrUndefined(signature.parameters); + var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + var contextualParameterType = getTypeOfSymbol(ts.last(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } @@ -44607,7 +44674,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 245 /* NamespaceImport */; + return !!declaration && declaration.kind === 245 /* NamespaceImport */; } } } @@ -44731,15 +44798,15 @@ var ts; if (strict && source.flags & (1 /* Any */ | 2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */)) { return false; } - return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || - (kind & 34 /* StringLike */ && isTypeAssignableTo(source, stringType)) || - (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || - (kind & 2048 /* Void */ && isTypeAssignableTo(source, voidType)) || - (kind & 16384 /* Never */ && isTypeAssignableTo(source, neverType)) || - (kind & 8192 /* Null */ && isTypeAssignableTo(source, nullType)) || - (kind & 4096 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || - (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || - (kind & 134217728 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + return !!(kind & 84 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 34 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 136 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 2048 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 16384 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 8192 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 4096 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 512 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 134217728 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { return source.flags & 131072 /* Union */ ? @@ -44747,7 +44814,7 @@ var ts; isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -44784,7 +44851,7 @@ var ts; if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 1536 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { + if (!(rightType.flags & 1 /* Any */ || isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -45150,6 +45217,8 @@ var ts; error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; + default: + return ts.Debug.fail(); } function checkSpecialAssignment(left, right) { var special = ts.getSpecialPropertyAssignmentKind(left.parent); @@ -45243,7 +45312,9 @@ var ts; } } var func = ts.getContainingFunction(node); - var functionFlags = func ? ts.getFunctionFlags(func) : 0 /* Normal */; + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); if (!(functionFlags & 1 /* Generator */)) { // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. return anyType; @@ -45262,7 +45333,7 @@ var ts; } } var isAsync = (functionFlags & 2 /* Async */) !== 0; - var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. @@ -45355,14 +45426,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768 /* TypeParameter */) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216 /* UnionOrIntersection */) { @@ -45374,19 +45437,17 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */ | 64 /* NumberLiteral */ | 1024 /* UniqueESSymbol */) || - constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 2 /* String */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + maybeTypeOfKind(constraint, 4 /* Number */) && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 512 /* ESSymbol */) && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + return !!(contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || contextualType.flags & 64 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || contextualType.flags & 128 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */); + contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */)); } return false; } @@ -45687,7 +45748,8 @@ var ts; } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), // TODO: GH#18217 + node.type, /*headMessage*/ undefined, leadingError); } } @@ -45839,20 +45901,21 @@ var ts; else { var isStatic = ts.hasModifier(member, 32 /* Static */); var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { switch (member.kind) { case 155 /* GetAccessor */: - addName(names, member.name, memberName, 1 /* Getter */); + addName(names, name, memberName, 1 /* Getter */); break; case 156 /* SetAccessor */: - addName(names, member.name, memberName, 2 /* Setter */); + addName(names, name, memberName, 2 /* Setter */); break; case 151 /* PropertyDeclaration */: - addName(names, member.name, memberName, 3 /* Property */); + addName(names, name, memberName, 3 /* Property */); break; case 153 /* MethodDeclaration */: - addName(names, member.name, memberName, 4 /* Method */); + addName(names, name, memberName, 4 /* Method */); break; } } @@ -45916,13 +45979,14 @@ var ts; var member = _a[_i]; if (member.kind === 150 /* PropertySignature */) { var memberName = void 0; - switch (member.name.kind) { + var name = member.name; + switch (name.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - memberName = member.name.text; + memberName = name.text; break; case 71 /* Identifier */: - memberName = ts.idText(member.name); + memberName = ts.idText(name); break; default: continue; @@ -46179,7 +46243,7 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -46578,7 +46642,7 @@ var ts; case 247 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: - ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); } } } @@ -46611,7 +46675,7 @@ var ts; if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 if (isTypeAny(thenFunction)) { return undefined; } @@ -46732,7 +46796,8 @@ var ts; var thenFunction = getTypeOfPropertyOfType(type, "then"); if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); + if (!diagnosticMessage) + return ts.Debug.fail(); error(errorNode, diagnosticMessage); } return undefined; @@ -46777,7 +46842,7 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); // TODO: GH#18217 var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (returnType === unknownType) { @@ -46852,19 +46917,23 @@ var ts; break; case 148 /* Parameter */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; case 151 /* PropertyDeclaration */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 153 /* MethodDeclaration */: case 155 /* GetAccessor */: case 156 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); + var methodType = getTypeOfNode(node.parent); // TODO: GH#18217 var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; + default: + return ts.Debug.fail(); } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } @@ -47199,13 +47268,6 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 231 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 147 /* TypeParameter */) { - return; - } - } var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } @@ -47283,6 +47345,7 @@ var ts; // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. var unusedImports = ts.createMap(); var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); nodeWithLocals.locals.forEach(function (local) { // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. // If it's a type parameter merged with a parameter, check if the parameter-side is used. @@ -47303,6 +47366,11 @@ var ts; addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + if (!isIdentifierThatStartsWithUnderScore(declaration.name) || !ts.isForInOrOfStatement(declaration.parent.parent)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + } else { var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); if (parameter) { @@ -47320,47 +47388,74 @@ var ts; unusedImports.forEach(function (_a) { var importClause = _a[0], unuseds = _a[1]; var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 245 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { var unused = unuseds_1[_i]; errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } } - else if (unuseds.length === 1) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); - } - else { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); - } }); unusedDestructures.forEach(function (_a) { var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; - if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 231 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 232 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } } - else if (bindingElements.length === 1) { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 213 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + } } }); } + function bindingNameText(name) { + switch (name.kind) { + case 71 /* Identifier */: + return ts.idText(name); + case 180 /* ArrayBindingPattern */: + case 179 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } function isImportedDeclaration(node) { return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */; } function importClauseFromImported(decl) { return decl.kind === 244 /* ImportClause */ ? decl : decl.kind === 245 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } - function forEachImportedDeclaration(importClause, cb) { - var defaultName = importClause.name, namedBindings = importClause.namedBindings; - return (defaultName && cb(importClause)) || - namedBindings && (namedBindings.kind === 245 /* NamespaceImport */ ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); - } function checkBlock(node) { // Grammar checking for SyntaxKind.Block if (node.kind === 212 /* Block */) { @@ -47426,6 +47521,7 @@ var ts; } return true; } + return false; }); } function checkIfNewTargetIsCapturedInEnclosingScope(node) { @@ -47440,6 +47536,7 @@ var ts; } return true; } + return false; }); } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -47640,7 +47737,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); @@ -47885,7 +47982,7 @@ var ts; } // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (rightType === neverType || !isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { + if (rightType === neverType || !(rightType.flags & 1 /* Any */ || isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */))) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -47918,7 +48015,7 @@ var ts; */ function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { if (inputType === neverType) { - reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 return undefined; } var uplevelIteration = languageVersion >= 2 /* ES2015 */; @@ -48068,11 +48165,11 @@ var ts; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); if (isTypeAny(methodType)) { return undefined; } - var signatures = methodType && getSignaturesOfType(methodType, 0 /* Call */); + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; if (!ts.some(signatures)) { if (errorNode) { // only report on the first error @@ -48205,7 +48302,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { // Grammar checking @@ -48330,6 +48427,7 @@ var ts; grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } + return false; }); } // ensure that label is unique @@ -48389,8 +48487,8 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; // Only process instance properties with computed names here. @@ -48414,7 +48512,7 @@ var ts; errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { @@ -48509,8 +48607,8 @@ var ts; if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { // Report an error on every conflicting declaration. var name = symbolToString(symbol); - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -48519,8 +48617,8 @@ var ts; function areTypeParametersIdentical(declarations, targetParameters) { var maxTypeArgumentCount = ts.length(targetParameters); var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; // If this declaration has too few or too many type parameters, we report an error var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); var numTypeParameters = sourceParameters.length; @@ -48741,7 +48839,7 @@ var ts; if (base.flags & 4194304 /* Prototype */) { continue; } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { @@ -48770,7 +48868,7 @@ var ts; // either base or derived property is private - not override, skip it continue; } - if (isPrototypeProperty(base) && isPrototypeProperty(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; } @@ -49015,7 +49113,11 @@ var ts; case 190 /* ParenthesizedExpression */: return evaluate(expr.expression); case 71 /* Identifier */: - return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); case 185 /* ElementAccessExpression */: case 184 /* PropertyAccessExpression */: var ex = expr; @@ -49115,8 +49217,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if ((declaration.kind === 234 /* ClassDeclaration */ || (declaration.kind === 233 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304 /* Ambient */)) { @@ -49169,7 +49271,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 && !inAmbientContext - && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -49300,7 +49402,7 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (ts.nodeIsMissing(moduleName)) { + if (!moduleName || ts.nodeIsMissing(moduleName)) { // Should be a parse error. return false; } @@ -49558,8 +49660,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -49582,11 +49684,11 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var tags = _a[_i].tags; - ts.forEach(tags, checkSourceElement); - } + if (ts.isInJavaScriptFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); } var kind = node.kind; if (cancellationToken) { @@ -49759,7 +49861,7 @@ var ts; if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } - var paramTag = parent.parent; + var paramTag = node.parent.parent; if (!ts.isJSDocParameterTag(paramTag)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); return; @@ -49777,8 +49879,8 @@ var ts; function getTypeFromJSDocVariadicType(node) { var type = getTypeFromTypeNode(node.type); var parent = node.parent; - var paramTag = parent.parent; - if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); if (host_1) { @@ -49817,8 +49919,8 @@ var ts; } } function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; + for (var _i = 0, _a = deferredNodes; _i < _a.length; _i++) { + var node = _a[_i]; switch (node.kind) { case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: @@ -49845,9 +49947,9 @@ var ts; function unusedIsError(kind) { switch (kind) { case 0 /* Local */: - return compilerOptions.noUnusedLocals; + return !!compilerOptions.noUnusedLocals; case 1 /* Parameter */: - return compilerOptions.noUnusedParameters; + return !!compilerOptions.noUnusedParameters; default: return ts.Debug.assertNever(kind); } @@ -50041,22 +50143,22 @@ var ts; case 236 /* TypeAliasDeclaration */: case 237 /* EnumDeclaration */: return true; + default: + return false; } } // True if the given identifier is part of a type reference - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 145 /* QualifiedName */) { + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 145 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 161 /* TypeReference */; + return node.parent.kind === 161 /* TypeReference */; } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 184 /* PropertyAccessExpression */) { + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 184 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */; + return node.parent.kind === 206 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -50088,10 +50190,10 @@ var ts; nodeOnRightSide = nodeOnRightSide.parent; } if (nodeOnRightSide.parent.kind === 242 /* ImportEqualsDeclaration */) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } if (nodeOnRightSide.parent.kind === 248 /* ExportAssignment */) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; } @@ -50229,25 +50331,27 @@ var ts; if (node.kind === 273 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } + var parent = node.parent; + var grandParent = parent.parent; if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(node.parent); + return getSymbolOfNode(parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); + return getSymbolOfNode(parent.parent); } if (node.kind === 71 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 181 /* BindingElement */ && - node.parent.parent.kind === 179 /* ObjectBindingPattern */ && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); + else if (parent.kind === 181 /* BindingElement */ && + grandParent.kind === 179 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; @@ -50297,10 +50401,10 @@ var ts; // falls through case 8 /* NumericLiteral */: // index access - var objectType = ts.isElementAccessExpression(node.parent) - ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined - : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) - ? getTypeFromTypeNode(node.parent.parent.objectType) + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79 /* DefaultKeyword */: @@ -50405,14 +50509,14 @@ var ts; // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { if (expr.parent.kind === 269 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern ts.Debug.assert(expr.parent.kind === 182 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); // TODO: GH#18217 } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -50483,9 +50587,9 @@ var ts; return target; } // Emitter support - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var isPropertyName_1 = node.parent.kind === 184 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; @@ -50518,13 +50622,12 @@ var ts; } } function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum // declaration, we need to start resolution at the declaration's container. @@ -50558,8 +50661,8 @@ var ts; } // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value @@ -50614,9 +50717,9 @@ var ts; // When resolved as an expression identifier, if the given node references a nested block scoped entity with // a name that either hides an existing name or might hide it when compiled downlevel, // return the declaration of that entity. Otherwise, return undefined. - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { @@ -50628,8 +50731,8 @@ var ts; } // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); if (node) { var symbol = getSymbolOfNode(node); if (symbol) { @@ -50648,7 +50751,7 @@ var ts; return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 249 /* ExportDeclaration */: var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); case 248 /* ExportAssignment */: return node.expression && node.expression.kind === 71 /* Identifier */ @@ -50657,8 +50760,8 @@ var ts; } return false; } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); if (node === undefined || node.parent.kind !== 273 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; @@ -50673,11 +50776,11 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return target.flags & 67216319 /* Value */ && + return !!(target.flags & 67216319 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { if (ts.isAliasSymbolDeclaration(node)) { @@ -50685,14 +50788,14 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } - var target = getSymbolLinks(symbol).target; + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } } if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); } return false; } @@ -50719,10 +50822,10 @@ var ts; return false; } function isRequiredInitializedParameter(parameter) { - return strictNullChecks && + return !!strictNullChecks && !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && - parameter.initializer && + !!parameter.initializer && !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { @@ -50732,7 +50835,7 @@ var ts; ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + return getNodeLinks(node).flags || 0; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -50761,11 +50864,11 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 65536 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 65536 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } - function getTypeReferenceSerializationKind(typeName, location) { + function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. - typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); if (!typeName) return ts.TypeReferenceSerializationKind.Unknown; if (location) { @@ -50789,7 +50892,7 @@ var ts; } // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -50826,8 +50929,8 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { - declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { return ts.createToken(119 /* AnyKeyword */); } @@ -50845,16 +50948,16 @@ var ts; } return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { - signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { return ts.createToken(119 /* AnyKeyword */); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { - expr = ts.getParseTreeNode(expr, ts.isExpression); + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { return ts.createToken(119 /* AnyKeyword */); } @@ -50880,9 +50983,9 @@ var ts; } return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); if (reference) { var symbol = getReferencedValueSymbol(reference); if (symbol) { @@ -50940,7 +51043,7 @@ var ts; }, getNodeCheckFlags: function (node) { node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; + return node ? getNodeCheckFlags(node) : 0; }, isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, @@ -50953,8 +51056,8 @@ var ts; createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, collectLinkedAliases: collectLinkedAliases, @@ -50967,14 +51070,14 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - isLateBound: function (node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { - accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; @@ -51069,7 +51172,7 @@ var ts; } function getExternalModuleFileFromDeclaration(declaration) { var specifier = declaration.kind === 238 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } @@ -51104,7 +51207,7 @@ var ts; }); } } - // We do global augmentations seperately from module augmentations (and before creating global types) because they + // We do global augmentations separately from module augmentations (and before creating global types) because they // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require // checking for an export or property on the module (if export=) which, in turn, can fall back to the @@ -51199,7 +51302,7 @@ var ts; case 16384 /* AsyncValues */: return "__asyncValues"; case 32768 /* ExportStar */: return "__exportStar"; case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; - default: ts.Debug.fail("Unrecognized helper"); + default: return ts.Debug.fail("Unrecognized helper"); } } function resolveHelpersModule(node, errorNode) { @@ -51407,7 +51510,7 @@ var ts; return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); @@ -51415,7 +51518,7 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); } - return; + return false; } else if ((node.kind === 243 /* ImportDeclaration */ || node.kind === 242 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); @@ -51429,6 +51532,7 @@ var ts; if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } + return false; } /** * true | false: Early return this value from checkGrammarModifiers. @@ -51499,6 +51603,7 @@ var ts; if (list && list.hasTrailingComma) { return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); } + return false; } function checkGrammarTypeParameterList(typeParameters, file) { if (typeParameters && typeParameters.length === 0) { @@ -51506,6 +51611,7 @@ var ts; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); } + return false; } function checkGrammarParameterList(parameters) { var seenOptionalParameter = false; @@ -51597,6 +51703,7 @@ var ts; if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } + return false; } function checkGrammarIndexSignature(node) { // Prevent cascading error by short-circuit @@ -51609,6 +51716,7 @@ var ts; var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); } + return false; } function checkGrammarTypeArguments(node, typeArguments) { return checkGrammarForDisallowedTrailingComma(typeArguments) || @@ -51623,6 +51731,7 @@ var ts; } } } + return false; } function checkGrammarArguments(args) { return checkGrammarForOmittedArgument(args); @@ -51636,7 +51745,7 @@ var ts; var listType = ts.tokenToString(node.token); return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } - return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + return ts.some(types, checkGrammarExpressionWithTypeArguments); } function checkGrammarExpressionWithTypeArguments(node) { return checkGrammarTypeArguments(node, node.typeArguments); @@ -51701,6 +51810,7 @@ var ts; if (computedPropertyName.expression.kind === 199 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } + return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { @@ -51716,9 +51826,7 @@ var ts; } } function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } + return !!questionToken && grammarErrorOnNode(questionToken, message); } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; @@ -51746,7 +51854,7 @@ var ts; } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 153 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); @@ -51781,7 +51889,7 @@ var ts; currentKind = 4 /* SetAccessor */; break; default: - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -51914,6 +52022,7 @@ var ts; } } } + return false; } /** Does the accessor have the right number of parameters? * A get accessor has no parameters or a single `this` parameter. @@ -52140,6 +52249,7 @@ var ts; } } } + return false; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 71 /* Identifier */) { @@ -52156,6 +52266,7 @@ var ts; } } } + return false; } function checkGrammarVariableDeclarationList(declarationList) { var declarations = declarationList.declarations; @@ -52165,6 +52276,7 @@ var ts; if (!declarationList.declarations.length) { return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } + return false; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { @@ -52216,6 +52328,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); @@ -52223,6 +52336,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorOnNode(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -52230,6 +52344,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; } + return false; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); @@ -52308,6 +52423,7 @@ var ts; } } } + return false; } function checkGrammarSourceFile(node) { return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); @@ -52341,6 +52457,7 @@ var ts; // Debug.assert(isStatement(node.parent)); } } + return false; } function checkGrammarNumericLiteral(node) { // Grammar checking @@ -52361,6 +52478,7 @@ var ts; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } + return false; } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -52369,6 +52487,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } + return false; } function getAmbientModules() { if (!ambientModulesCache) { @@ -52398,6 +52517,7 @@ var ts; if (ts.isSpreadElement(nodeArguments[0])) { return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); } + return false; } } ts.createTypeChecker = createTypeChecker; @@ -52482,7 +52602,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). if (node === undefined) { - return undefined; + return node; } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; @@ -52587,7 +52707,6 @@ var ts; return name; } ts.createUniqueName = createUniqueName; - /** Create a unique name based on the supplied text. */ function createOptimisticUniqueName(text) { var name = createIdentifier(text); name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; @@ -53290,7 +53409,7 @@ var ts; function createPropertyAccess(expression, name) { var node = createSynthesizedNode(184 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); - node.name = asName(name); + node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); return node; } @@ -54013,6 +54132,7 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0 /* None */; } var node = createSynthesizedNode(232 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); @@ -54134,6 +54254,7 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0 /* None */; } var node = createSynthesizedNode(238 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); @@ -54564,7 +54685,7 @@ var ts; ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { var node = createSynthesizedNode(271 /* SpreadAssignment */); - node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } ts.createSpreadAssignment = createSpreadAssignment; @@ -54635,6 +54756,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -54861,6 +54984,7 @@ var ts; return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); } ts.createExternalModuleExport = createExternalModuleExport; + // Utilities function asName(name) { return ts.isString(name) ? createIdentifier(name) : name; } @@ -55391,7 +55515,7 @@ var ts; // Utilities function createForOfBindingStatement(node, boundValue) { if (ts.isVariableDeclarationList(node)) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); + var firstDeclaration = ts.first(node.declarations); var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, /*typeNode*/ undefined, boundValue); return ts.setTextRange(ts.createVariableStatement( @@ -55448,6 +55572,7 @@ var ts; } } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } var callee = skipOuterExpressions(expression, 7 /* All */); var thisArg; var target; @@ -55539,7 +55664,7 @@ var ts; switch (property.kind) { case 155 /* GetAccessor */: case 156 /* SetAccessor */: - return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); case 269 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); case 270 /* ShorthandPropertyAssignment */: @@ -55558,7 +55683,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, - /*type*/ undefined, getAccessor.body); + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); @@ -55569,7 +55695,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, - /*type*/ undefined, setAccessor.body); + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); @@ -55600,7 +55727,8 @@ var ts; return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, - /*type*/ undefined, method.body), + /*type*/ undefined, method.body // TODO: GH#18217 + ), /*location*/ method), /*original*/ method)), /*location*/ method), @@ -55683,6 +55811,7 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { var name = ts.getMutableClone(nodeName); @@ -55726,7 +55855,7 @@ var ts; function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); ts.setTextRange(qualifiedName, name); - var emitFlags; + var emitFlags = 0; if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -55741,7 +55870,8 @@ var ts; } ts.convertToFunctionBody = convertToFunctionBody; function convertFunctionDeclarationToExpression(node) { - ts.Debug.assert(!!node.body); + if (!node.body) + return ts.Debug.fail(); var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); @@ -55801,15 +55931,9 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - /** - * Add just the custom prologue-directives into target statement-array. - * The function needs to be called during each transformation step. - * This function needs to be called whenever we transform the statement - * list of a source file, namespace, or function-like body. - */ function addCustomPrologue(target, source, statementOffset, visitor) { var numStatements = source.length; - while (statementOffset < numStatements) { + while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); @@ -56383,7 +56507,7 @@ var ts; * Otherwise, a new StringLiteral node representing the module name will be returned. */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { - var moduleName = ts.getExternalModuleName(importNode); + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 if (moduleName.kind === 9 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) @@ -56441,8 +56565,9 @@ var ts; // `1` in `({ a: b = 1 } = ...)` // `1` in `({ a: {b} = 1 } = ...)` // `1` in `({ a: [b] = 1 } = ...)` - return ts.isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true) - ? bindingElement.initializer.right + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right : undefined; } if (ts.isShorthandPropertyAssignment(bindingElement)) { @@ -57522,7 +57647,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -57680,7 +57805,7 @@ var ts; return ts.some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { - return e.propertyName && e.propertyName.escapedText === "default" /* Default */; + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; } function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; @@ -57715,7 +57840,7 @@ var ts; ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) - return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -57942,7 +58067,7 @@ var ts; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: true, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -58003,7 +58128,7 @@ var ts; } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; function bindingOrAssignmentElementAssignsToName(element, escapedName) { - var target = ts.getTargetOfBindingOrAssignmentElement(element); + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isBindingOrAssignmentPattern(target)) { return bindingOrAssignmentPatternAssignsToName(target, escapedName); } @@ -58034,13 +58159,14 @@ var ts; * @param level Indicates the extent to which flattening should occur. */ function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } var pendingExpressions; var pendingDeclarations = []; var declarations = []; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: hoistTempVariables, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -58068,7 +58194,7 @@ var ts; } else { context.hoistVariableDeclaration(temp); - var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + var pendingDeclaration = ts.last(pendingDeclarations); pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); pendingDeclaration.value = temp; @@ -58122,7 +58248,7 @@ var ts; value = ts.createVoidZero(); } } - var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } @@ -58130,7 +58256,7 @@ var ts; flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } else { - flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 } } /** @@ -58182,7 +58308,7 @@ var ts; flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); bindingElements = undefined; } - var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); } } @@ -58956,7 +59082,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -60043,7 +60169,8 @@ var ts; * @param node The type reference node. */ function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -60069,8 +60196,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } /** @@ -60579,7 +60707,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -60628,7 +60756,7 @@ var ts; * @param node The module declaration node. */ function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -60820,7 +60948,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -61219,7 +61347,7 @@ var ts; // constructor references in static property initializers. var declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { - var classAlias = classAliases[declaration.id]; + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { var clone_1 = ts.getSynthesizedClone(classAlias); ts.setSourceMapRange(clone_1, node); @@ -61421,7 +61549,7 @@ var ts; } function visitCatchClauseInAsyncBody(node) { var catchClauseNames = ts.createUnderscoreEscapedMap(); - recordDeclarationName(node.variableDeclaration, catchClauseNames); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 // names declared in a catch variable are block scoped var catchClauseUnshadowedNames; catchClauseNames.forEach(function (_, escapedName) { @@ -61461,8 +61589,9 @@ var ts; : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } function visitForStatementInAsyncBody(node) { - return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) - ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } /** @@ -61554,10 +61683,10 @@ var ts; } } function isVariableDeclarationListWithCollidingName(node) { - return node + return !!node && ts.isVariableDeclarationList(node) && !(node.flags & 3 /* BlockScoped */) - && ts.forEach(node.declarations, collidesWithParameterName); + && node.declarations.some(collidesWithParameterName); } function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { hoistVariableDeclarationList(node); @@ -61629,7 +61758,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -62228,7 +62357,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -62256,7 +62385,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -62545,14 +62674,16 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + 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(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -63209,7 +63340,7 @@ var ts; hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 && node.kind === 224 /* ReturnStatement */ && !node.expression; } @@ -63349,7 +63480,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -63424,7 +63555,8 @@ var ts; (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; - if (!node.label) { + var label = node.label; + if (!label) { if (node.kind === 223 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; @@ -63437,12 +63569,12 @@ var ts; } else { if (node.kind === 223 /* BreakStatement */) { - labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(node.label), labelMarker); + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } else { - labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(node.label), labelMarker); + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -63603,7 +63735,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -63661,7 +63793,7 @@ var ts; // `super` call. // If this is the case, we do not include the synthetic `...args` parameter and // will instead use the `arguments` object in ES5/3. - return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } /** @@ -63697,7 +63829,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -63716,7 +63848,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -64163,7 +64295,7 @@ var ts; // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); - ts.setSourceMapRange(target, firstAccessor.name); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); ts.setSourceMapRange(propertyName, firstAccessor.name); @@ -64359,7 +64491,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { @@ -64497,13 +64629,12 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 /* ContainsBindingPattern */ - && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); if (firstDeclaration) { - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); } } return declarationList; @@ -64657,11 +64788,12 @@ var ts; } function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { var statements = []; - if (ts.isVariableDeclarationList(node.initializer)) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { if (node.initializer.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - var firstOriginalDeclaration = ts.firstOrUndefined(node.initializer.declarations); + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { // This works whether the declaration is a var, let, or const. // It will use rhsIterationValue _a[_i] as the initializer. @@ -64670,9 +64802,7 @@ var ts; ts.setOriginalNode(declarationList, node.initializer); // Adjust the source map range for the first declaration to align with the old // emitter. - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); statements.push(ts.createVariableStatement( /*modifiers*/ undefined, declarationList)); } @@ -64683,20 +64813,20 @@ var ts; /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), /*type*/ undefined, boundValue) - ]), ts.moveRangePos(node.initializer, -1)), node.initializer)), ts.moveRangeEnd(node.initializer, -1))); + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); } } else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. - var assignment = ts.createAssignment(node.initializer, boundValue); + var assignment = ts.createAssignment(initializer, boundValue); if (ts.isDestructuringAssignment(assignment)) { ts.aggregateTransformFlags(assignment); statements.push(ts.createStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); } else { - assignment.end = node.initializer.end; - statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); } } if (convertedLoopBodyStatements) { @@ -64940,7 +65070,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -65178,7 +65308,7 @@ var ts; case 156 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; case 153 /* MethodDeclaration */: @@ -65340,7 +65470,7 @@ var ts; function visitArrayLiteralExpression(node) { if (node.transformFlags & 64 /* ES2015 */) { // We are here because we contain a SpreadElementExpression. - return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } return ts.visitEachChild(node, visitor, context); } @@ -65395,11 +65525,11 @@ var ts; var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); // The class statements are the statements generated by visiting the first statement with initializer of the // body (1), while all other statements are added to remainingStatements (2) - var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); - var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); // We know there is only one variable declaration here as we verified this in an // earlier call to isTypeScriptClassWrapper var variable = varStatement.declarationList.declarations[0]; @@ -65885,14 +66015,13 @@ var ts; * @param node An original source tree node. */ function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { + switch (node.parent.kind) { case 181 /* BindingElement */: case 234 /* ClassDeclaration */: case 237 /* EnumDeclaration */: case 231 /* VariableDeclaration */: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); } return false; } @@ -66123,7 +66252,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -66308,6 +66437,7 @@ var ts; case 4 /* Yield */: return "yield"; case 5 /* YieldStar */: return "yield*"; case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 } } function transformGenerators(context) { @@ -66615,7 +66745,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -66671,13 +66801,14 @@ var ts; * @param node The node to visit. */ function visitBinaryExpression(node) { - switch (ts.getExpressionAssociativity(node)) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { case 0 /* Left */: return visitLeftAssociativeBinaryExpression(node); case 1 /* Right */: return visitRightAssociativeBinaryExpression(node); default: - ts.Debug.fail("Unknown associativity."); + return ts.Debug.assertNever(assoc); } } function isCompoundAssignment(kind) { @@ -67685,7 +67816,7 @@ var ts; beginExceptionBlock(); transformAndEmitEmbeddedStatement(node.tryBlock); if (node.catchClause) { - beginCatchBlock(node.catchClause.variableDeclaration); + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 transformAndEmitEmbeddedStatement(node.catchClause.block); } if (node.finallyBlock) { @@ -67699,7 +67830,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -67800,7 +67931,8 @@ var ts; */ function endBlock() { var block = peekBlock(); - ts.Debug.assert(block !== undefined, "beginBlock was never called."); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); var index = blockActions.length; blockActions[index] = 1 /* Close */; blockOffsets[index] = operations ? operations.length : 0; @@ -68133,7 +68265,7 @@ var ts; * @param label A label. */ function createLabel(label) { - if (label > 0) { + if (label !== undefined && label > 0) { if (labelExpressions === undefined) { labelExpressions = []; } @@ -68851,7 +68983,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -69045,7 +69177,7 @@ var ts; if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { return undefined; } - var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 var expr = getHelperExpressionForImport(node, name); if (expr === name) { return undefined; @@ -69074,7 +69206,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -70343,8 +70475,8 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependRange(statements, endLexicalEnvironment()); - var exportStarFunction = addExportStarIfNeeded(statements); + ts.prependStatements(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), ts.createPropertyAssignment("execute", ts.createFunctionExpression( @@ -70480,7 +70612,7 @@ var ts; var statements = []; for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { case 243 /* ImportDeclaration */: if (!entry.importClause) { @@ -70566,7 +70698,7 @@ var ts; function visitImportDeclaration(node) { var statements; if (node.importClause) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -70586,7 +70718,7 @@ var ts; function visitImportEqualsDeclaration(node) { ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); var statements; - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); @@ -71087,7 +71219,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -71131,9 +71263,6 @@ var ts; * @param node The node to visit. */ function visitForInitializer(node) { - if (!node) { - return node; - } if (shouldHoistForInitializer(node)) { var expressions = void 0; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { @@ -71817,7 +71946,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 231 /* VariableDeclaration */ || node.kind === 181 /* BindingElement */) { @@ -71952,7 +72081,7 @@ var ts; ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; break; default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); } return { diagnosticMessage: diagnosticMessage, @@ -72021,7 +72150,7 @@ var ts; ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; default: - ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); } } function getTypeParameterConstraintVisibilityError() { @@ -72059,7 +72188,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } return { diagnosticMessage: diagnosticMessage, @@ -72231,7 +72360,7 @@ var ts; var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) - return; // Omit declaration files from bundle results, too + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -72463,7 +72592,7 @@ var ts; } if (ts.isBindingPattern(elem.name)) { // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible - return ts.forEach(elem.name.elements, getBindingNameVisible); + return ts.some(elem.name.elements, getBindingNameVisible); } else { return resolver.isDeclarationVisible(elem); @@ -72471,11 +72600,11 @@ var ts; } function updateParamsList(node, params, modifierMask) { if (ts.hasModifier(node, 8 /* Private */)) { - return undefined; + return undefined; // TODO: GH#18217 } var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); if (!newParams) { - return undefined; + return undefined; // TODO: GH#18217 } return ts.createNodeArray(newParams, params.hasTrailingComma); } @@ -72505,7 +72634,7 @@ var ts; } function rewriteModuleSpecifier(parent, input) { if (!input) - return; + return undefined; // TODO: GH#18217 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 238 /* ModuleDeclaration */ && parent.kind !== 178 /* ImportType */); if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -72674,7 +72803,9 @@ var ts; case 154 /* Constructor */: { var isPrivate = ts.hasModifier(input, 8 /* Private */); // A constructor declaration may not have a type annotation - var ctor = ts.createSignatureDeclaration(154 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + var ctor = ts.createSignatureDeclaration(154 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), /*type*/ undefined); ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); return cleanup(ctor); @@ -72874,7 +73005,7 @@ var ts; needsDeclare = false; ts.visitNode(inner, visitDeclarationStatements); // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) - var id = "" + ts.getOriginalNodeId(inner); + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); return cleanup(ts.updateModuleDeclaration(input, @@ -72924,7 +73055,7 @@ var ts; var extendsClause_1 = ts.getClassExtendsHeritageClauseElement(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression - var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -72943,7 +73074,7 @@ var ts; return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); })); return [statement, cleanup(ts.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); @@ -73731,7 +73862,7 @@ var ts; } if (node) { var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.sourceMapRange; var _a = range || node, pos = _a.pos, end = _a.end; var source = range && range.source; @@ -73779,7 +73910,7 @@ var ts; return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { @@ -73826,7 +73957,7 @@ var ts; */ function getText() { if (disabled) { - return; + return undefined; // TODO: GH#18217 } encodeLastRecordedSourceMapSpan(); return JSON.stringify({ @@ -73844,7 +73975,7 @@ var ts; */ function getSourceMappingURL() { if (disabled) { - return; + return undefined; // TODO: GH#18217 } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url @@ -73905,7 +74036,7 @@ var ts; var currentLineMap; var detachedCommentsInfo; var hasWrittenComment = false; - var disabled = printerOptions.removeComments; + var disabled = !!printerOptions.removeComments; return { reset: reset, setWriter: setWriter, @@ -73923,7 +74054,7 @@ var ts; if (node) { hasWrittenComment = false; var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. @@ -74211,11 +74342,11 @@ var ts; detachedCommentsInfo = undefined; } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { // get the leading comments from detachedPos - var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -74270,6 +74401,7 @@ var ts; * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. */ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { @@ -74300,7 +74432,7 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { @@ -74371,7 +74503,7 @@ var ts; emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, - sourceMaps: sourceMapDataList + sourceMaps: sourceMapDataList, }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -74478,7 +74610,7 @@ var ts; ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); // Write bundled offset information if applicable if (bundleInfoPath) { bundleInfo.totalLength = writer.getTextPos(); @@ -74662,7 +74794,7 @@ var ts; } } function setWriter(output) { - writer = output; + writer = output; // TODO: GH#18217 comments.setWriter(output); } function reset() { @@ -74720,8 +74852,7 @@ var ts; return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode); - onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); + ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); } function pipelineEmitWithComments(hint, node) { ts.Debug.assertDefined(emitNodeWithComments); @@ -74733,9 +74864,8 @@ var ts; pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assertDefined(onEmitSourceMapOfNode); ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */); - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); + ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { if (hint === 0 /* SourceFile */) @@ -75988,7 +76118,7 @@ var ts; writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emitIdentifierName(node.name); + emitIdentifierName(node.name); // TODO: GH#18217 emitSignatureAndBody(node, emitSignatureHead); } function emitBlockCallback(_hint, body) { @@ -76357,7 +76487,7 @@ var ts; } function emitJsxAttribute(node) { emit(node.name); - emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); @@ -76491,7 +76621,7 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) @@ -76719,7 +76849,7 @@ var ts; emitNodeList(emit, parentNode, children, format, start, count); } function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { switch (format & 28 /* DelimitersMask */) { @@ -76745,7 +76875,7 @@ var ts; if (isUndefined && format & 8192 /* OptionalIfUndefined */) { return; } - var isEmpty = isUndefined || start >= children.length || count === 0; + var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 16384 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -76758,6 +76888,7 @@ var ts; if (format & 7680 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -76777,7 +76908,7 @@ var ts; // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; - if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } @@ -76790,7 +76921,7 @@ var ts; } // Emit each child. var previousSibling = void 0; - var shouldDecreaseIndentAfterEmit = void 0; + var shouldDecreaseIndentAfterEmit = false; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -76868,6 +76999,7 @@ var ts; } if (format & 7680 /* BracketsMask */) { if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -77396,7 +77528,7 @@ var ts; * Generates a unique name for an ImportDeclaration or ExportDeclaration. */ function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 var baseName = ts.isStringLiteral(expr) ? ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); @@ -77458,7 +77590,7 @@ var ts; case 3 /* Unique */: return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); } - ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } /** * Gets the node from which a name should be generated. @@ -77921,8 +78053,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); - var mtimeBefore = ts.sys.getModifiedTime(fileName); + var hash = ts.sys.createHash(data); // TODO: GH#18217 + var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -77934,7 +78066,7 @@ var ts; } } ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); + var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -78005,7 +78137,7 @@ var ts; function formatDiagnostic(diagnostic, host) { 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 _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 var fileName = diagnostic.file.fileName; var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; @@ -78052,7 +78184,7 @@ var ts; var context_2 = ""; if (diagnostic.file) { var start = diagnostic.start, length_4 = diagnostic.length, file_9 = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; + var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 var _b = ts.getLineAndCharacterOfPosition(file_9, start + length_4), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file_9, file_9.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file_9.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_9.fileName; @@ -78196,8 +78328,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -78228,9 +78359,9 @@ var ts; }; } function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { - var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; - var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; + var oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -78257,7 +78388,7 @@ var ts; // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); - host = host || createCompilerHost(options); + var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); @@ -78285,7 +78416,7 @@ var ts; } else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -78293,7 +78424,7 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -78427,7 +78558,7 @@ var ts; } else if (options.composite) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -78548,7 +78679,7 @@ var ts; // `result[i]` is either a `ResolvedModuleFull` or a marker. // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + result[i] = undefined; // TODO: GH#18217 } } else { @@ -78561,7 +78692,7 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same @@ -78657,7 +78788,7 @@ var ts; var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; } @@ -78843,7 +78974,7 @@ var ts; return nodes; } function isSourceFileFromExternalLibrary(file) { - return sourceFilesFoundSearchingNodeModules.get(file.path); + return !!sourceFilesFoundSearchingNodeModules.get(file.path); } function isSourceFileDefaultLibrary(file) { if (file.hasNoDefaultLib) { @@ -78859,7 +78990,7 @@ var ts; return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } } function getDiagnosticsProducingTypeChecker() { @@ -78912,7 +79043,8 @@ var ts; var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -79003,11 +79135,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } /** @@ -79017,7 +79157,7 @@ var ts; var file = diagnostic.file, start = diagnostic.start; if (file) { var lineStarts = ts.getLineStarts(file); - var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 while (line > 0) { var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); @@ -79224,7 +79364,7 @@ var ts; if (cachedResult) { return cachedResult; } - var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 if (sourceFile) { if (!cache.perFile) { cache.perFile = ts.createMap(); @@ -79404,7 +79544,8 @@ var ts; } /** This has side effects through `findSourceFile`. */ function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -79496,7 +79637,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 redirectTargetsSet.set(fileFromPackageId.path, true); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -79591,7 +79732,7 @@ var ts; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 } else { // If we already resolved to this file, it must have been a secondary reference. Check file contents @@ -79601,7 +79742,8 @@ var ts; if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } } // don't overwrite previous resolution result @@ -79614,7 +79756,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 } if (saveResolution) { resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); @@ -79718,7 +79860,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(host, ref); // TODO: GH#18217 // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -79729,13 +79871,13 @@ var ts; return { commandLine: commandLine, sourceFile: sourceFile }; } function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); } function getDeclarationOutputDirectory(proj) { return proj.options.declarationDir || proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); + ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !options.strictNullChecks) { @@ -79990,9 +80132,9 @@ var ts; if (ts.isObjectLiteralExpression(pathProp.initializer)) { for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { var keyProps = _b[_a]; - if (ts.isArrayLiteralExpression(keyProps.initializer) && - keyProps.initializer.elements.length > valueIndex) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); needCompilerDiagnostic = false; } } @@ -80053,7 +80195,7 @@ var ts; if (_referencesArrayLiteralSyntax === undefined) { _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword if (options.configFile) { - var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { var prop = _a[_i]; if (ts.isArrayLiteralExpression(prop.initializer)) { @@ -80095,6 +80237,7 @@ var ts; return false; } programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + return false; // TODO: GH#18217 This function always returns `false`!` } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); @@ -80114,6 +80257,10 @@ var ts; if (out) { return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } // If --outDir, check if file is in that directory if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); @@ -80121,8 +80268,8 @@ var ts; if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); - return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts" /* Ts */)) || - !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx" /* Tsx */)); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); } return false; } @@ -80247,7 +80394,7 @@ var ts; if (!resolvedTypeReferenceDirective) { return; } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); @@ -80279,7 +80426,7 @@ var ts; for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var version_1 = sourceFile.version; - var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -80342,7 +80489,8 @@ var ts; return false; } var info = state.fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); + if (!info) + return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { @@ -80354,7 +80502,7 @@ var ts; latestSignature = computeHash(emitOutput.outputFiles[0].text); } else { - latestSignature = prevSignature; + latestSignature = prevSignature; // TODO: GH#18217 } } cacheToUpdateSignature.set(sourceFile.path, latestSignature); @@ -80489,8 +80637,9 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { - queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); } } } @@ -80505,7 +80654,7 @@ var ts; (function (ts) { function hasSameKeys(map1, map2) { // Has same size and every key is present in both maps - return map1 === map2 || map1 && map2 && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); } /** * Create the state so that we can iterate on changedFiles/affected files @@ -80533,7 +80682,7 @@ var ts; } // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; - var oldReferencedMap = useOldState && oldState.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -80577,7 +80726,7 @@ var ts; var affectedFiles = state.affectedFiles; if (affectedFiles) { var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; - var affectedFilesIndex = state.affectedFilesIndex; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 while (affectedFilesIndex < affectedFiles.length) { var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.path)) { @@ -80690,7 +80839,7 @@ var ts; // Return same program if underlying program doesnt change var oldState = oldProgram && oldProgram.getState(); if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { - newProgram = undefined; + newProgram = undefined; // TODO: GH#18217 oldState = undefined; return oldProgram; } @@ -80704,7 +80853,7 @@ var ts; var computeHash = host.createHash || ts.identity; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); // To ensure that we arent storing any references to old program or new program without state - newProgram = undefined; + newProgram = undefined; // TODO: GH#18217 oldProgram = undefined; oldState = undefined; var result = { @@ -80765,7 +80914,7 @@ var ts; if (!targetSourceFile) { // Emit and report any errors we ran into. var sourceMaps = []; - var emitSkipped = void 0; + var emitSkipped = false; var diagnostics = void 0; var emittedFiles = []; var affectedEmitResult = void 0; @@ -80885,7 +81034,7 @@ var ts; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; - var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. // The key in the map is source file's path. @@ -80906,7 +81055,7 @@ var ts; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); - var rootPath = rootDir && resolutionHost.toPath(rootDir); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames var typeRootsWatches = ts.createMap(); return { @@ -80964,7 +81113,7 @@ var ts; } // Invalidated if file has unresolved imports var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); - return value && !!value.length; + return !!value && !!value.length; } function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { @@ -80974,7 +81123,7 @@ var ts; } var collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = undefined; - return function (path) { return (collected && collected.has(path)) || + return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { @@ -81055,7 +81204,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -81126,7 +81275,7 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - return { dir: rootDir, dirPath: rootPath }; + return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } @@ -81190,7 +81339,7 @@ var ts; } } if (setAtRoot) { - setDirectoryWatcher(rootDir, rootPath); + setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 } } function setDirectoryWatcher(dir, dirPath, subDirectory) { @@ -81339,7 +81488,7 @@ var ts; // Resolution is invalidated if the resulting file name is same as the deleted file path function (resolution, getResolutionWithResolvedFileName) { var result = getResolutionWithResolvedFileName(resolution); - return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 }); } function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { @@ -81395,7 +81544,7 @@ var ts; return rootPath; } var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info @@ -81462,7 +81611,7 @@ var ts; getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, getNewLine: function () { return ts.sys.newLine; }, getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) - } : undefined; + } : undefined; // TODO: GH#18217 /** * Create a function that reports error by writing to the system and handles the formating of the diagnostic */ @@ -81479,7 +81628,7 @@ var ts; return function (diagnostic) { diagnostics[0] = diagnostic; system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); - diagnostics[0] = undefined; + diagnostics[0] = undefined; // TODO: GH#18217 }; } ts.createDiagnosticReporter = createDiagnosticReporter; @@ -81539,7 +81688,7 @@ var ts; var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); - host.onUnRecoverableConfigFileDiagnostic = undefined; + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; @@ -81669,9 +81818,9 @@ var ts; * Creates the watch compiler host from system for config file in watch mode */ function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { - reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); - var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; return host; @@ -81691,7 +81840,7 @@ var ts; (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -81718,7 +81867,7 @@ var ts; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; - var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } @@ -81748,7 +81897,7 @@ var ts; var trace = host.trace && (function (s) { host.trace(s + newLine); }); var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : compilerOptions.diagnostis ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); @@ -81770,7 +81919,7 @@ var ts; readFile: readFile, trace: trace, directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), realpath: host.realpath && (function (s) { return host.realpath(s); }), getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), onReleaseOldSourceFile: onReleaseOldSourceFile, @@ -82059,12 +82208,12 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; - configFileSpecs = configFileParseResult.configFileSpecs; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } @@ -82443,6 +82592,13 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, + { + name: "strictAny", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_any_type + }, { name: "strictNullChecks", type: "boolean", @@ -82948,7 +83104,7 @@ var ts; case "string": return ts.map(values, function (v) { return v || ""; }); default: - return ts.filter(ts.map(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }), function (v) { return !!v; }); + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); } } ts.parseListTypeOption = parseListTypeOption; @@ -83371,6 +83527,7 @@ var ts; var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } + return false; } /** * Generate tsconfig configuration when running command line "--init" @@ -83423,7 +83580,7 @@ var ts; } else { if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 } else { // There is a typeMap associated with this command-line option so use it to map value back to its name @@ -83850,13 +84007,10 @@ var ts; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return undefined; + return false; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; + return typeof result === "boolean" && result; } function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; @@ -83885,7 +84039,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -84282,7 +84436,7 @@ var ts; if (optionEnumValue === value) { return optionStringValue; } - }); + }); // TODO: GH#18217 } } })(ts || (ts = {})); @@ -84710,7 +84864,7 @@ var ts; ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { var target = climbPastPropertyAccess(node); - return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -84773,6 +84927,8 @@ var ts; return true; case 177 /* LiteralType */: return node.parent.parent.kind === 175 /* IndexedAccessType */; + default: + return false; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -84946,7 +85102,7 @@ var ts; } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { + if (n === undefined || ts.nodeIsMissing(n)) { return false; } switch (n.kind) { @@ -84996,7 +85152,7 @@ var ts; // having at least a closing paren. return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); case 238 /* ModuleDeclaration */: - return n.body && isCompletedNode(n.body, sourceFile); + return !!n.body && isCompletedNode(n.body, sourceFile); case 216 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); @@ -85066,11 +85222,11 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last_2 = ts.lastOrUndefined(children); - if (last_2.kind === expectedLastToken) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { return true; } - else if (last_2.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -85130,6 +85286,7 @@ var ts; ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { + if (includeEndPosition === void 0) { includeEndPosition = false; } return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, includeEndPosition, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; @@ -85344,10 +85501,11 @@ var ts; var tokenKind = token.kind; var remainingMatchingTokens = 0; while (true) { - token = findPrecedingToken(token.getFullStart(), sourceFile); - if (!token) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { return undefined; } + token = preceding; if (token.kind === matchingTokenKind) { if (remainingMatchingTokens === 0) { return token; @@ -85360,21 +85518,24 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(token, sourceFile) { + function isPossiblyTypeArgumentPosition(tokenIn, sourceFile) { + var token = tokenIn; // This function determines if the node could be type argument position // Since during editing, when type argument list is not complete, // the tree could be of any shape depending on the tokens parsed before current node, // scanning of the previous identifier followed by "<" before current node would give us better result // Note that we also balance out the already provided type arguments, arrays, object literals while doing so var remainingLessThanTokens = 0; + var nTypeArguments = 0; while (token) { switch (token.kind) { case 27 /* LessThanToken */: // Found the beginning of the generic argument expression token = findPrecedingToken(token.getFullStart(), sourceFile); - var tokenIsIdentifier = token && ts.isIdentifier(token); - if (!remainingLessThanTokens || !tokenIsIdentifier) { - return tokenIsIdentifier; + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return { called: token, nTypeArguments: nTypeArguments }; } remainingLessThanTokens--; break; @@ -85392,24 +85553,26 @@ var ts; // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); if (!token) - return false; + return undefined; break; case 20 /* CloseParenToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); if (!token) - return false; + return undefined; break; case 22 /* CloseBracketToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); if (!token) - return false; + return undefined; break; // Valid tokens in a type name. Skip. case 26 /* CommaToken */: + nTypeArguments++; + break; case 36 /* EqualsGreaterThanToken */: case 71 /* Identifier */: case 9 /* StringLiteral */: @@ -85429,11 +85592,11 @@ var ts; break; } // Invalid token in type - return false; + return undefined; } token = findPrecedingToken(token.getFullStart(), sourceFile); } - return false; + return undefined; } ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; /** @@ -85636,7 +85799,7 @@ var ts; } ts.repeatString = repeatString; function skipConstraint(type) { - return type.isTypeParameter() ? type.getConstraint() : type; + return type.isTypeParameter() ? type.getConstraint() : type; // TODO: GH#18217 } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { @@ -85662,16 +85825,16 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier) { + function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) - : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier, preferences.quotePreference === "single") : moduleSpecifier); } ts.makeImport = makeImport; function symbolNameNoDefault(symbol) { @@ -85897,18 +86060,21 @@ var ts; } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { - typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); @@ -85916,7 +86082,7 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return location.parent && + return !!location.parent && (location.parent.kind === 247 /* ImportSpecifier */ || location.parent.kind === 251 /* ExportSpecifier */) && location.parent.propertyName === location; } @@ -85944,7 +86110,7 @@ var ts; scriptKinds[_i - 2] = arguments[_i]; } var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); } ts.scriptKindIs = scriptKindIs; function getScriptKind(fileName, host) { @@ -86356,6 +86522,8 @@ var ts; case 9 /* text */: case 17 /* parameterName */: return ts.TokenClass.Identifier; + default: + return undefined; // TODO: GH#18217 Debug.assertNever(type); } } /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ @@ -86603,6 +86771,7 @@ var ts; case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; case 23 /* jsxText */: return "jsx text" /* jsxText */; case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type); } } function convertClassificationsToSpans(classifications) { @@ -86859,19 +87028,20 @@ var ts; } if (ts.isPunctuation(tokenKind)) { if (token) { + var parent = token.parent; if (tokenKind === 58 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 231 /* VariableDeclaration */ || - token.parent.kind === 151 /* PropertyDeclaration */ || - token.parent.kind === 148 /* Parameter */ || - token.parent.kind === 261 /* JsxAttribute */) { + if (parent.kind === 231 /* VariableDeclaration */ || + parent.kind === 151 /* PropertyDeclaration */ || + parent.kind === 148 /* Parameter */ || + parent.kind === 261 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 199 /* BinaryExpression */ || - token.parent.kind === 197 /* PrefixUnaryExpression */ || - token.parent.kind === 198 /* PostfixUnaryExpression */ || - token.parent.kind === 200 /* ConditionalExpression */) { + if (parent.kind === 199 /* BinaryExpression */ || + parent.kind === 197 /* PrefixUnaryExpression */ || + parent.kind === 198 /* PostfixUnaryExpression */ || + parent.kind === 200 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -86881,6 +87051,7 @@ var ts; return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { + // TODO: GH#18217 return token.parent.kind === 261 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 12 /* RegularExpressionLiteral */) { @@ -87006,7 +87177,7 @@ var ts; // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; - }); + }); // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } @@ -87210,8 +87381,8 @@ var ts; // after the last '/' that appears in the fragment because that's where the replacement span // starts if (fragmentDirectory !== undefined) { - var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); - return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); }); + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); } return nonRelativeModuleNames; } @@ -87321,7 +87492,7 @@ var ts; } return result; } - // Replace everything after the last directory seperator that appears + // Replace everything after the last directory separator that appears function getDirectoryFragmentTextSpan(text, textStart) { var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); var offset = index !== -1 ? index + 1 : 0; @@ -87366,7 +87537,7 @@ var ts; return ts.directoryProbablyExists(path, host); } catch ( /*ignore*/_a) { /*ignore*/ } - return undefined; + return false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; @@ -87414,7 +87585,7 @@ var ts; } var contextToken = ts.findPrecedingToken(position, sourceFile); if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) - return undefined; + return undefined; // TODO: GH#18217 if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined @@ -87424,7 +87595,7 @@ var ts; && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(program, log, sourceFile, position, preferences, /*detailsEntryId*/ undefined); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); if (!completionData) { return undefined; } @@ -87494,9 +87665,9 @@ var ts; }] }; } var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { + if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); + getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -87514,6 +87685,9 @@ var ts; } return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } function isMemberCompletionKind(kind) { switch (kind) { case 0 /* ObjectPropertyDeclaration */: @@ -87632,7 +87806,7 @@ var ts; continue; } // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 uniques.set(name, true); } entries.push(entry); @@ -87728,7 +87902,7 @@ var ts; case 186 /* CallExpression */: case 187 /* NewExpression */: if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); // f("/*completion position*/") @@ -87783,7 +87957,8 @@ var ts; : ts.emptyArray; } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { - var completionData = getCompletionData(program, log, sourceFile, position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); if (!completionData) { return { type: "none" }; } @@ -87797,7 +87972,7 @@ var ts; // completion entry. return ts.firstDefined(symbols, function (symbol) { var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - var info = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, origin, completionKind); + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; @@ -87819,7 +87994,7 @@ var ts; var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); - return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); @@ -87840,7 +88015,7 @@ var ts; case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; - return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. @@ -87905,12 +88080,15 @@ var ts; CompletionKind[CompletionKind["None"] = 5] = "None"; })(CompletionKind || (CompletionKind = {})); function getRecommendedCompletion(currentToken, position, sourceFile, checker) { - var ty = getContextualType(currentToken, position, sourceFile, checker); - var symbol = ty && ty.symbol; - // Don't include make a recommended completion for an abstract class - return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) - ? getFirstSymbolInChain(symbol, currentToken, checker) - : undefined; + var contextualType = getContextualType(currentToken, position, sourceFile, checker); + // For a union, return the first one with a recommended completion. + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, currentToken, checker) + : undefined; + }); } function getContextualType(currentToken, position, sourceFile, checker) { var parent = currentToken.parent; @@ -87920,7 +88098,7 @@ var ts; case 58 /* EqualsToken */: switch (parent.kind) { case 231 /* VariableDeclaration */: - return checker.getContextualType(parent.initializer); + return checker.getContextualType(parent.initializer); // TODO: GH#18217 case 199 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); case 261 /* JsxAttribute */: @@ -87935,7 +88113,7 @@ var ts; case 17 /* OpenBraceToken */: return ts.isJsxExpression(parent) && parent.parent.kind !== 254 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: - var argInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(currentToken, position, sourceFile); + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(currentToken, position, sourceFile); return argInfo // At `,`, treat this as the next argument after the comma. ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (currentToken.kind === 26 /* CommaToken */ ? 1 : 0)) @@ -87974,7 +88152,7 @@ var ts; function isModuleSymbol(symbol) { return symbol.declarations.some(function (d) { return d.kind === 273 /* SourceFile */; }); } - function getCompletionData(program, log, sourceFile, position, preferences, detailsEntryId) { + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 @@ -88046,7 +88224,7 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217 log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file @@ -88055,7 +88233,7 @@ var ts; // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { var start_4 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } // Find the node where completion is requested on. @@ -88086,6 +88264,7 @@ var ts; node = parent.left; break; case 178 /* ImportType */: + case 209 /* MetaProperty */: node = parent; break; default: @@ -88195,6 +88374,8 @@ var ts; case 294 /* JSDocTypeTag */: case 296 /* JSDocTypedefTag */: return true; + default: + return false; } } function getTypeScriptMemberSymbols() { @@ -88232,13 +88413,18 @@ var ts; } } } + if (ts.isMetaProperty(node) && (node.keywordToken === 94 /* NewKeyword */ || node.keywordToken === 91 /* ImportKeyword */)) { + var completion = (node.keywordToken === 94 /* NewKeyword */) ? "target" : "meta"; + symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); + return; + } if (!isTypeLocation) { addTypeProperties(typeChecker.getTypeAtLocation(node)); } } function addTypeProperties(type) { isNewIdentifierLocation = hasIndexSignature(type); - if (ts.isSourceFileJavaScript(sourceFile)) { + if (isUncheckedFile) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that // each individual type has. This is because we're going to add all identifiers @@ -88377,7 +88563,7 @@ var ts; if (ts.programContainsEs6Modules(program)) return true; // For JS, stay on the safe side. - if (ts.isSourceFileJavaScript(sourceFile)) + if (isUncheckedFile) return false; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); @@ -88457,6 +88643,7 @@ var ts; // symbol can be referenced at locations where type is allowed return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); } + return false; } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { var tokenTextLowerCase = tokenText.toLowerCase(); @@ -88539,7 +88726,7 @@ var ts; return true; } if (contextToken.parent.kind === 257 /* JsxClosingElement */ || contextToken.parent.kind === 255 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 254 /* JsxElement */; + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 254 /* JsxElement */; } } return false; @@ -88696,7 +88883,7 @@ var ts; // cursor is in an import clause // try to show exported member for imported module var moduleSpecifier = (namedImportsOrExports.kind === 246 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; completionKind = 3 /* MemberLike */; @@ -88723,7 +88910,7 @@ var ts; if (!ts.isClassLike(decl)) return 1 /* Success */; var classElement = contextToken.parent; - var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; // If this is context token is not something we are editing now, consider if this would lead to be modifier if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { @@ -88739,7 +88926,7 @@ var ts; if (!(classElementModifierFlags & 8 /* Private */)) { // List of property symbols of base type that are not private and already implemented var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { - var type = typeChecker.getTypeAtLocation(baseTypeNode); + var type = typeChecker.getTypeAtLocation(baseTypeNode); // TODO: GH#18217 return typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); }); symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); @@ -88774,13 +88961,14 @@ var ts; */ function tryGetConstructorLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 19 /* OpenParenToken */: case 26 /* CommaToken */: - return ts.isConstructorDeclaration(contextToken.parent) && contextToken.parent; + return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; default: if (isConstructorParameterCompletion(contextToken)) { - return contextToken.parent.parent; + return parent.parent; } } } @@ -88797,6 +88985,7 @@ var ts; return true; } prev_1 = node; + return false; }); return container && container; } @@ -88862,7 +89051,8 @@ var ts; * @returns true if we are certain that the currently edited location must define a new location; false otherwise. */ function isSolelyIdentifierDefinitionLocation(contextToken) { - var containingNodeKind = contextToken.parent.kind; + var parent = contextToken.parent; + var containingNodeKind = parent.kind; switch (contextToken.kind) { case 26 /* CommaToken */: return containingNodeKind === 231 /* VariableDeclaration */ || @@ -88875,9 +89065,9 @@ var ts; containingNodeKind === 236 /* TypeAliasDeclaration */ || // type Map, K, | // class A= contextToken.pos); + (ts.isClassLike(parent) && + !!parent.typeParameters && + parent.typeParameters.end >= contextToken.pos); case 23 /* DotToken */: return containingNodeKind === 180 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: @@ -88896,15 +89086,14 @@ var ts; containingNodeKind === 236 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 151 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); + return containingNodeKind === 151 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 148 /* Parameter */ || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 180 /* ArrayBindingPattern */); // var [...z| + (!!parent.parent && parent.parent.kind === 180 /* ArrayBindingPattern */); // var [...z| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 148 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); + return containingNodeKind === 148 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 118 /* AsKeyword */: return containingNodeKind === 247 /* ImportSpecifier */ || containingNodeKind === 251 /* ExportSpecifier */ || @@ -89005,7 +89194,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 181 /* BindingElement */ && m.propertyName) { + if (ts.isBindingElement(m) && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 71 /* Identifier */) { existingName = m.propertyName.escapedText; @@ -89018,7 +89207,7 @@ var ts; var name = ts.getNameOfDeclaration(m); existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } - existingMemberNames.set(existingName, true); + existingMemberNames.set(existingName, true); // TODO: GH#18217 } return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); } @@ -89255,7 +89444,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) + return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -89337,7 +89526,7 @@ var ts; if (!sourceFilesSet.has(fileName)) { ts.Debug.assert(program.redirectTargetsSet.has(fileName)); var redirectTarget_1 = program.getSourceFile(fileName); - var redirect = ts.find(sourceFilesToSearch, function (f) { return f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; ts.Debug.assert(sourceFilesSet.has(fileName)); } @@ -89410,7 +89599,7 @@ var ts; } else if (ts.isTryStatement(node)) { // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. - return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), aggregateOwnedThrowStatements(node.finallyBlock)); + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); } // Do not cross function boundaries. return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); @@ -89451,7 +89640,7 @@ var ts; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; + return !!actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { @@ -89502,9 +89691,8 @@ var ts; } case 154 /* Constructor */: case 153 /* MethodDeclaration */: - case 233 /* FunctionDeclaration */: { + case 233 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - } case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: var nodes = container.members; @@ -89720,6 +89908,11 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. @@ -89733,7 +89926,7 @@ var ts; if (!bucket && createIfMissing) { buckets.set(key, bucket = ts.createMap()); } - return bucket; + return bucket; // TODO: GH#18217 } function reportStats() { var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { @@ -89742,8 +89935,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -89774,13 +89966,26 @@ var ts; var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } @@ -89789,7 +89994,10 @@ var ts; // the script snapshot. If so, update it appropriately. Otherwise, we can just // return it as is. if (entry.sourceFile.version !== version) { - entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } // If we're acquiring, then this is the first time this LS is asking for this document. // Increase our ref count so we know there's another LS using the document. If we're @@ -89800,6 +90008,7 @@ var ts; entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -89817,6 +90026,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -89824,11 +90040,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -89965,7 +90182,7 @@ var ts; ts.Debug.assert(!isAvailableThroughGlobal); var isNew = markSeenIndirectUser(sourceFileLike); if (isNew) { - indirectUserDeclarations.push(sourceFileLike); + indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217 } return isNew; } @@ -90046,7 +90263,7 @@ var ts; return; } if (exportKind === 0 /* Named */) { - searchForNamedImport(namedBindings); + searchForNamedImport(namedBindings); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) } else { // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals @@ -90110,7 +90327,7 @@ var ts; /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); - return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { if (!ts.isExportDeclaration(statement)) return; var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; @@ -90216,12 +90433,13 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; + var grandParent = parent.parent; if (symbol.exportSymbol) { if (parent.kind === 184 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) - ? getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ false) + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) : undefined; } else { @@ -90248,15 +90466,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(parent.parent)) { - return getExportAssignmentExport(parent.parent); + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(parent.parent)) { - return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -90331,6 +90549,9 @@ var ts; else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } // If a reference is a class expression, the exported node would be its parent. @@ -90626,6 +90847,7 @@ var ts; } var moduleReferences = ts.emptyArray; var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; if (moduleSourceFile) { var exportEquals = symbol.exports.get("export=" /* ExportEquals */); // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. @@ -90634,13 +90856,13 @@ var ts; return moduleReferences; // Continue to get references to 'export ='. symbol = ts.skipAlias(exportEquals, checker); - node = undefined; + referencedNode = undefined; } - return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; function isModuleSymbol(symbol) { - return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile); + return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; } function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); @@ -90718,7 +90940,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -90826,7 +91048,7 @@ var ts; State.prototype.getImportSearches = function (exportSymbol, exportInfo) { if (!this.importTracker) this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); - return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); }; /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { @@ -90837,7 +91059,7 @@ var ts; // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** @@ -90938,8 +91160,9 @@ var ts; } } function getPropertySymbolOfDestructuringAssignment(location, checker) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - checker.getPropertySymbolOfDestructuringAssignment(location); + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; } function getObjectBindingElementWithoutPropertyName(symbol) { var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */); @@ -90998,8 +91221,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -91018,7 +91241,7 @@ var ts; // declare module "a" { export type T = number; } // declare module "b" { import { T } from "a"; export const x: T; } // 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; + return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 } /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ function isSymbolReferencedInFile(definition, checker, sourceFile) { @@ -91210,7 +91433,8 @@ var ts; if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - ts.Debug.assert(!!exportInfo); + if (!exportInfo) + return ts.Debug.fail(); searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. @@ -91346,8 +91570,7 @@ var ts; } /** Find references to `super` in the constructor of an extending class. */ function findSuperConstructorAccesses(cls, addNode) { - var symbol = cls.symbol; - var ctr = symbol.members.get("__constructor" /* Constructor */); + var ctr = cls.symbol.members.get("__constructor" /* Constructor */); if (!ctr) { return; } @@ -91690,7 +91913,7 @@ var ts; var name = ts.getNameFromPropertyName(node.name); var symbol = contextualType && name && contextualType.getProperty(name); return symbol ? [symbol] : - contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; + contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; // TODO: GH#18217 } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations @@ -91712,8 +91935,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -91774,6 +91997,72 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { + var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; + var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); + if (newPath !== undefined) { + var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); + changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); + } + } + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); + if (oldFile) { + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + } + } + function isRef(toUpdate) { + return "fileName" in toUpdate; + } + function getImportsToUpdate(program, oldFilePath, host) { + var result = []; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var ref = _c[_b]; + if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { + result.push({ sourceFile: sourceFile, toUpdate: ref }); + } + } + for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { + var importStringLiteral = _e[_d]; + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + // We may or may not have picked up on the file being renamed, so maybe successfully resolved to oldFilePath, or maybe that's in failedLookupLocations + if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { + result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); + } + } + } + return result; + } + function getPathUpdater(oldFilePath, newFilePath, host) { + // Get the relative path from old to new location, and append it on to the end of imports and normalize. + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + return function (oldPath) { + if (!ts.pathIsRelative(oldPath)) + return; + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + }; + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -91786,10 +92075,11 @@ var ts; if (node === sourceFile) { return undefined; } + var parent = node.parent; // Labels if (ts.isJumpStatementTarget(node)) { var label = ts.getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } var typeChecker = program.getTypeChecker(); var symbol = getSymbol(node, typeChecker); @@ -91805,7 +92095,7 @@ var ts; // If this is the original constructor definition, parent is the class. return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) || // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias - symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); }) + symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); }) ? [sigInfo] : [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node)); } @@ -91829,9 +92119,9 @@ var ts; // pr/*destination*/op1: number // } // bar(({pr/*goto*/op1})=>{}); - if (ts.isPropertyName(node) && ts.isBindingElement(node.parent) && ts.isObjectBindingPattern(node.parent.parent) && - (node === (node.parent.propertyName || node.parent.name))) { - var type = typeChecker.getTypeAtLocation(node.parent.parent); + if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var type = typeChecker.getTypeAtLocation(parent.parent); if (type) { var propSymbols = ts.getPropertySymbolsFromType(type, node); if (propSymbols) { @@ -91866,7 +92156,7 @@ var ts; var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - var file_17 = reference && program.getSourceFile(reference.resolvedFileName); + var file_17 = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 return file_17 && { fileName: typeReferenceDirective.fileName, file: file_17 }; } return undefined; @@ -92009,14 +92299,14 @@ var ts; kind: "script" /* scriptElement */, name: name, containerName: undefined, - containerKind: undefined + containerKind: undefined, }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ function getAncestorCallLikeExpression(node) { var target = climbPastManyPropertyAccesses(node); var callLike = target.parent; - return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; } function climbPastManyPropertyAccesses(node) { return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; @@ -92220,7 +92510,7 @@ var ts; if (!ts.isIdentifier(param.name)) return undefined; var name = param.name.text; - if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217 || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { return undefined; } @@ -92378,7 +92668,7 @@ var ts; return rightHandSide.parameters; case 204 /* ClassExpression */: { var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); - return ctr && ctr.parameters; + return ctr ? ctr.parameters : ts.emptyArray; } } return ts.emptyArray; @@ -92589,7 +92879,7 @@ var ts; return result; function addInferredTyping(typingName) { if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); + inferredTypings.set(typingName, undefined); // TODO: GH#18217 } } function addInferredTypings(typingNames, message) { @@ -92740,7 +93030,7 @@ var ts; case 0 /* Ok */: return ts.Debug.fail(); // Shouldn't have called this. default: - ts.Debug.assertNever(result); + throw ts.Debug.assertNever(result); } } JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; @@ -92784,12 +93074,12 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { - var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); // TODO: GH#18217 if (fullMatch) { rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); } @@ -92854,12 +93144,12 @@ var ts; return undefined; } // Now, walk up our containers, adding all their names to the container array. - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { return undefined; } - declaration = ts.getContainerNode(declaration); + container = ts.getContainerNode(container); } return containers; } @@ -92882,7 +93172,7 @@ var ts; textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ // TODO: GH#18217 Just use `container ? ...` }; } })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); @@ -93216,6 +93506,7 @@ var ts; // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { + // TODO: GH#18217 return a.body.kind === b.body.kind && (a.body.kind !== 238 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ @@ -93237,7 +93528,7 @@ var ts; children.sort(compareChildren); } function compareChildren(child1, child2) { - return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217 || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); } /** @@ -93251,7 +93542,7 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName) { - return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { case 191 /* FunctionExpression */: @@ -93359,7 +93650,7 @@ var ts; } } function hasSomeImportantChild(item) { - return ts.forEach(item.children, function (child) { + return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); return childKind !== 231 /* VariableDeclaration */ && childKind !== 181 /* BindingElement */; }); @@ -93428,7 +93719,7 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 238 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 238 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217 } function isComputedProperty(member) { return !member.name || member.name.kind === 146 /* ComputedPropertyName */; @@ -93501,7 +93792,7 @@ var ts; organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; - var ambientModuleBody = getModuleBlock(ambientModule); + var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); @@ -93549,12 +93840,12 @@ var ts; OrganizeImports.organizeImports = organizeImports; function getModuleBlock(moduleDecl) { var body = moduleDecl.body; - return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -93592,8 +93883,8 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - // The JSX factory symbol is always used. - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { @@ -93619,16 +93910,16 @@ var ts; if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { // Add the namespace import to the existing default ImportDeclaration. var defaultImport = defaultImports[0]; - coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217 return coalescedImports; } var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); - }); + }); // TODO: GH#18217 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, /*name*/ undefined, namespaceImport.importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217 } if (defaultImports.length === 0 && namedImports.length === 0) { return coalescedImports; @@ -93641,10 +93932,10 @@ var ts; 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.importClause.name)); + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] @@ -93655,7 +93946,7 @@ var ts; : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) - : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); return coalescedImports; /* @@ -93749,7 +94040,8 @@ var ts; } OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier); } function sortSpecifiers(specifiers) { return ts.stableSort(specifiers, function (s1, s2) { @@ -93773,73 +94065,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); - return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { - var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; - var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); - if (newPath !== undefined) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } - }); - } - ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); - } - } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var checker = program.getTypeChecker(); - var result = []; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (!program.getSourceFileFromReference(sourceFile, ref) && ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - // If it resolved to something already, ignore. - if (checker.getSymbolAtLocation(importStringLiteral)) - continue; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } - } - return result; - } - function getPathUpdater(oldFilePath, newFilePath, host) { - // Get the relative path from old to new location, and append it on to the end of imports and normalize. - var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; - } - function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); - } -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { @@ -94075,7 +94300,7 @@ var ts; // First, check that the last part of the dot separated pattern matches the name of the // candidate. If not, then there's no point in proceeding and doing the more // expensive work. - var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments), stringToWordSpans); + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); if (!candidateMatch) { return undefined; } @@ -94808,7 +95033,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, 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 @@ -94827,7 +95052,7 @@ var ts; } } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -94899,6 +95124,7 @@ var ts; }; } function getRenameInfoError(diagnostic) { + // TODO: GH#18217 return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), @@ -94944,7 +95170,12 @@ var ts; ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); + })(ArgumentListKind || (ArgumentListKind = {})); + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + })(InvocationKind || (InvocationKind = {})); function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { var typeChecker = program.getTypeChecker(); // Decide whether to show signature help @@ -94958,11 +95189,9 @@ var ts; return undefined; cancellationToken.throwIfCancellationRequested(); // Semantic filtering of signature help - var call = argumentInfo.invocation; - var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker); cancellationToken.throwIfCancellationRequested(); - if (!candidates.length) { + if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. if (ts.isSourceFileJavaScript(sourceFile)) { @@ -94970,54 +95199,76 @@ var ts; } return undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { - if (argumentInfo.invocation.kind !== 186 /* CallExpression */) { - return undefined; + function getCandidateInfo(argumentInfo, checker) { + var invocation = argumentInfo.invocation; + if (invocation.kind === 0 /* Call */) { + var candidates = []; + var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; } + else { + var type = checker.getTypeAtLocation(invocation.called); // TODO: GH#18217 + var signatures = ts.isNewExpression(invocation.called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + var candidates = signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= argumentInfo.argumentCount; }); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + } + function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { // See if we can find some symbol with the call expression name that has call signatures. - var callExpression = argumentInfo.invocation; - var expression = callExpression.expression; + var expression = getExpressionFromInvocation(argumentInfo.invocation); var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + var _loop_16 = function (sourceFile) { var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_16 = function (declaration) { + var _loop_17 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); if (type) { var callSignatures_1 = type.getCallSignatures(); if (callSignatures_1 && callSignatures_1.length) { - return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, typeChecker); }) }; + return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; } } } }; - for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { - var declaration = declarations_12[_b]; - var state_5 = _loop_16(declaration); - if (typeof state_5 === "object") - return state_5.value; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var state_6 = _loop_17(declaration); + if (typeof state_6 === "object") + return state_6; } } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var state_5 = _loop_16(sourceFile); + if (typeof state_5 === "object") + return state_5.value; } } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.kind === 0 /* TypeArguments */ || info.invocation.kind === 1 /* TypeArgs */ ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; /** * Returns relevant information for the argument list and the current argument if we are * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (ts.isCallOrNewExpression(node.parent)) { - var invocation = node.parent; + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; var list = void 0; var argumentIndex = void 0; // There are 3 cases to handle: @@ -95037,7 +95288,7 @@ var ts; if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); + list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); ts.Debug.assert(list !== undefined); argumentIndex = 0; } @@ -95053,60 +95304,66 @@ var ts; return undefined; argumentIndex = getArgumentIndex(list, node); } - var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; + var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; var argumentCount = getArgumentCount(list); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + return { kind: kind, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 188 /* TaggedTemplateExpression */) { + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { - return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); + return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 188 /* TaggedTemplateExpression */) { - var templateExpression = node.parent; + else if (ts.isTemplateHead(node) && parent.parent.kind === 188 /* TaggedTemplateExpression */) { + var templateExpression = parent; var tagExpression = templateExpression.parent; ts.Debug.assert(templateExpression.kind === 201 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 210 /* TemplateSpan */ && node.parent.parent.parent.kind === 188 /* TaggedTemplateExpression */) { - var templateSpan = node.parent; - var templateExpression = templateSpan.parent; - var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 201 /* TemplateExpression */); + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; // If we're just after a template tail, don't show signature help. if (node.kind === 16 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } - var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position); return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent && ts.isJsxOpeningLikeElement(node.parent)) { + else if (ts.isJsxOpeningLikeElement(parent)) { // Provide a signature help for JSX opening element or JSX self-closing element. // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") // i.e // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } // 0 && ts.lastOrUndefined(listChildren).kind === 26 /* CommaToken */) { + if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -95183,7 +95440,7 @@ var ts; } return { kind: 2 /* TaggedTemplateArguments */, - invocation: tagExpression, + invocation: { kind: 0 /* Call */, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, argumentCount: argumentCount @@ -95215,7 +95472,7 @@ var ts; // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === 201 /* TemplateExpression */) { - var lastSpan = ts.lastOrUndefined(template.templateSpans); + var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } @@ -95223,39 +95480,40 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 273 /* SourceFile */; n = n.parent) { - if (ts.isFunctionBlock(n)) { - return undefined; - } + var _loop_18 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. - if (n.pos < n.parent.pos || n.end > n.parent.end) { - ts.Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); - } + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); if (argumentInfo) { - return argumentInfo; + return { value: argumentInfo }; } - // TODO: Handle generic call with incomplete syntax + }; + for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { + var state_7 = _loop_18(n); + if (typeof state_7 === "object") + return state_7.value; } return undefined; } - SignatureHelp.getContainingArgumentInfo = getContainingArgumentInfo; function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { var children = parent.getChildren(sourceFile); var indexOfOpenerToken = children.indexOf(openerToken); ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var callTarget = ts.getInvokedExpression(invocation); - var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); + var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.called; + var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); var printer = ts.createPrinter({ removeComments: true }); - var items = ts.map(candidates, function (candidateSignature) { + var items = candidates.map(function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; var suffixDisplayParts = []; @@ -95270,9 +95528,9 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); }); ts.addRange(suffixDisplayParts, parameterParts); } @@ -95280,8 +95538,8 @@ var ts; isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); - printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); } }); ts.addRange(prefixDisplayParts, typeParameterParts); @@ -95294,10 +95552,10 @@ var ts; writer.writeSpace(" "); var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); if (predicate) { - typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + typeChecker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); } else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); } }); ts.addRange(suffixDisplayParts, returnTypeParts); @@ -95319,8 +95577,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: parameter.name, @@ -95331,8 +95589,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, @@ -95362,8 +95620,7 @@ var ts; case 233 /* FunctionDeclaration */: case 191 /* FunctionExpression */: if (isJsFile) { - var symbol = node.symbol; - if (symbol.members && (symbol.members.size > 0)) { + if (node.symbol.members && (node.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)); } } @@ -95402,6 +95659,7 @@ var ts; } } } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; @@ -95412,7 +95670,7 @@ var ts; case 213 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); + }); // TODO: GH#18217 case 215 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) @@ -95432,7 +95690,7 @@ var ts; switch (node.kind) { case 243 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings.kind === 245 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 245 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; case 242 /* ImportEqualsDeclaration */: @@ -95576,7 +95834,7 @@ var ts; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - var hasAddedSymbolInfo; + var hasAddedSymbolInfo = false; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; var printer; @@ -95610,7 +95868,7 @@ var ts; } if (callExpressionLike) { var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 var useConstructSignatures = callExpressionLike.kind === 187 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { @@ -95676,7 +95934,7 @@ var ts; if (locationIsSymbolDeclaration) { var allSignatures = functionDeclaration_1.kind === 154 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; @@ -95764,12 +96022,13 @@ var ts; else { // Method/function type parameter var decl = ts.getDeclarationOfKind(symbol, 147 /* TypeParameter */); - ts.Debug.assert(decl !== undefined); + if (decl === undefined) + return ts.Debug.fail(); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); - var signature = typeChecker.getSignatureFromDeclaration(declaration); + var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 if (declaration.kind === 158 /* ConstructSignature */) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); @@ -96009,6 +96268,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0 /* None */; } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); @@ -96094,7 +96354,7 @@ var ts; options.noResolve = true; // if jsx is specified then treat file as .tsx var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); - var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217 if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } @@ -96135,7 +96395,8 @@ var ts; } // Emit program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } ts.transpileModule = transpileModule; @@ -96158,7 +96419,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_19 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -96177,7 +96438,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_19(opt); } return options; } @@ -96314,7 +96575,7 @@ var ts; lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */; } else { scanner.scan(); @@ -97068,7 +97329,7 @@ var ts; } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - context.contextNode.decorators && + !!context.contextNode.decorators && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -97373,7 +97634,7 @@ var ts; return ts.rangeContainsRange(parent.members, node); case 238 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 239 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + return !!body && body.kind === 239 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); case 273 /* SourceFile */: case 212 /* Block */: case 239 /* ModuleBlock */: @@ -97407,7 +97668,7 @@ var ts; } // pick only errors that fall in range var sorted = errors - .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217 .sort(function (e1, e2) { return e1.start - e2.start; }); if (!sorted.length) { return rangeHasNoErrors; @@ -97535,7 +97796,7 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); + processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217 trimTrailingWhitespacesForRemainingRange(); } } @@ -97896,6 +98157,7 @@ var ts; } } } + // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAction = 0 /* None */; @@ -98368,7 +98630,7 @@ var ts; // handle cases when codefix is about to be inserted before the close brace ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 : lineAtPosition !== currentStart.line ? options.indentSize : 0; - return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 } // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); @@ -98377,7 +98639,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; + return actualIndentation + options.indentSize; // TODO: GH#18217 } previous = current; current = current.parent; @@ -98674,8 +98936,9 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { case 215 /* ExpressionStatement */: case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: @@ -98697,7 +98960,6 @@ var ts; case 186 /* CallExpression */: case 187 /* NewExpression */: case 213 /* VariableStatement */: - case 231 /* VariableDeclaration */: case 248 /* ExportAssignment */: case 224 /* ReturnStatement */: case 200 /* ConditionalExpression */: @@ -98720,22 +98982,14 @@ var ts; case 246 /* NamedImports */: case 251 /* ExportSpecifier */: case 247 /* ImportSpecifier */: - case 269 /* PropertyAssignment */: case 151 /* PropertyDeclaration */: return true; - } - return false; - } - function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { - var childKind = child ? child.kind : 0 /* Unknown */; - switch (parent.kind) { case 231 /* VariableDeclaration */: case 269 /* PropertyAssignment */: - case 183 /* ObjectLiteralExpression */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183 /* ObjectLiteralExpression */) { + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } - break; + return true; case 217 /* DoStatement */: case 218 /* WhileStatement */: case 220 /* ForInStatement */: @@ -98759,6 +99013,12 @@ var ts; return childKind !== 257 /* JsxClosingElement */; case 258 /* JsxFragment */: return childKind !== 260 /* JsxClosingFragment */; + case 169 /* IntersectionType */: + case 168 /* UnionType */: + if (childKind === 165 /* TypeLiteral */) { + return false; + } + // falls through } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -98788,7 +99048,7 @@ var ts; */ function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; @@ -98905,7 +99165,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 183 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 183 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -99358,7 +99618,7 @@ var ts; var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); } return changes; }; @@ -99383,14 +99643,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_20 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_18(i); + _loop_20(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -99399,8 +99659,12 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter) { - var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; @@ -99414,7 +99678,7 @@ var ts; 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(change.options.joiner || newLineCharacter) + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217 : format(change.node); // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); @@ -99457,7 +99721,7 @@ var ts; return ts.skipTrivia(s, 0) === s.length; } function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217 // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); @@ -99877,7 +100141,7 @@ var ts; case 161 /* TypeReference */: return transformJSDocTypeReference(node); default: - var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 ts.setEmitFlags(visited, 1 /* SingleLine */); return visited; } @@ -99896,7 +100160,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 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); @@ -99981,7 +100245,7 @@ var ts; precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { - copyComments(precedingNode, newClassDeclaration, sourceFile); + copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 deleteNode(precedingNode); } else { @@ -100153,13 +100417,13 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); } } }); @@ -100167,7 +100431,7 @@ var ts; return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -100177,7 +100441,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, preferences)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -100188,14 +100452,14 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { 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); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -100230,10 +100494,10 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { switch (statement.kind) { case 213 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); return false; case 215 /* ExpressionStatement */: { var expression = statement.expression; @@ -100241,7 +100505,7 @@ var ts; case 186 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], preferences)); } return false; } @@ -100256,7 +100520,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -100269,11 +100533,11 @@ var ts; } else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); } } // Move it out to its own variable statement. (This will not be used if `!foundImport`) @@ -100285,22 +100549,22 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { switch (name.kind) { case 179 /* ObjectBindingPattern */: case 180 /* 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), + makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), 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)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } function convertAssignment(sourceFile, checker, assignment, changes, exports) { @@ -100432,7 +100696,7 @@ var ts; } function exportConst() { // `exports.x = 0;` --> `export const x = 0;` - return makeConst(modifiers, ts.createIdentifier(name), exported); + return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217 } } /** @@ -100440,16 +100704,16 @@ var ts; * 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) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { switch (name.kind) { case 179 /* 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); - }); + }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) if (importSpecifiers) { - return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, preferences)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -100460,21 +100724,21 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, preferences), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); default: - ts.Debug.assertNever(name); + return 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) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { 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(); @@ -100509,7 +100773,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -100549,10 +100813,10 @@ var ts; 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) { + function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, preferences) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -100677,7 +100941,9 @@ var ts; ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, ], - getCodeActions: getImportCodeActions, + getCodeActions: function (context) { return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(context) + : getActionsForNonUMDImport(context); }, // TODO: GH#20315 fixIds: [], getAllCodeActions: ts.notImplemented, @@ -100696,7 +100962,6 @@ var ts; program: program, checker: checker, compilerOptions: program.getCompilerOptions(), - cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(context.host)), symbolName: symbolName, symbolToken: symbolToken, @@ -100742,9 +101007,17 @@ var ts; return result; } function getCodeActionsForImport_separateExistingAndNew(exportInfos, context, useExisting, addNew) { - var existingImports = ts.flatMap(exportInfos, function (info) { - return getImportDeclarations(info, context.checker, context.sourceFile, context.cachedImportDeclarations); - }); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, context.checker, context.sourceFile); }); + ts.append(useExisting, tryUseExistingNamespaceImport(existingImports, context, context.symbolToken, context.checker)); + var addToExisting = tryAddToExistingImport(existingImports, context); + if (addToExisting) { + useExisting.push(addToExisting); + } + else { // Don't bother providing an action to add a new import if we can add to an existing one. + getCodeActionsForAddImport(exportInfos, context, existingImports, addNew); + } + } + function tryUseExistingNamespaceImport(existingImports, context, symbolToken, checker) { // It is possible that multiple import statements with the same specifier exist in the file. // e.g. // @@ -100757,19 +101030,28 @@ var ts; // 1. change "member3" to "ns.member3" // 2. add "member3" to the second import statement's import list // and it is up to the user to decide which one fits best. - if (context.symbolToken && ts.isIdentifier(context.symbolToken)) { - for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) { - var declaration = existingImports_1[_i].declaration; - var namespace_2 = getNamespaceImportName(declaration); - if (namespace_2) { - var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2)); - if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken)); - } + return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = namespace && checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { + return getCodeActionForUseExistingNamespaceImport(namespace.text, context, symbolToken); } } - } - getCodeActionsForAddImport(exportInfos, context, existingImports, useExisting, addNew); + }); + } + function tryAddToExistingImport(existingImports, context) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind === 243 /* ImportDeclaration */ && declaration.importClause) { + var changes = tryUpdateExistingImport(context, declaration.importClause, importKind); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [context.symbolName, moduleSpecifierWithoutQuotes], changes); + } + } + }); } function getNamespaceImportName(declaration) { if (declaration.kind === 243 /* ImportDeclaration */) { @@ -100780,21 +101062,14 @@ var ts; return declaration.name; } } - // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? - function getImportDeclarations(_a, checker, _b, cachedImportDeclarations) { + function getExistingImportDeclarations(_a, checker, _b) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; var imports = _b.imports; - if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } - var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (moduleSpecifier) { - var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 243 /* ImportDeclaration */ || i.kind === 242 /* ImportEqualsDeclaration */) - && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; - }); - } - return cached; + return ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 243 /* ImportDeclaration */ || i.kind === 242 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); } function getCodeActionForNewImport(context, _a) { var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; @@ -100819,7 +101094,7 @@ var ts; }); // if this file doesn't have any import statements, insert an import statement and then insert a new line // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. + // are there are already a new line separating code and import statements. return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } function shouldUseSingleQuote(sourceFile, preferences) { @@ -100853,21 +101128,7 @@ var ts; // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { - var fromExistingImport = ts.firstDefined(existingImports, function (_a) { - var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 243 /* ImportDeclaration */ && declaration.importClause) { - var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined, importKind); - if (changes) { - var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); - return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes); - } - } - }); - if (fromExistingImport) { - useExisting.push(fromExistingImport); - return; - } + function getCodeActionsForAddImport(exportInfos, ctx, existingImports, addNew) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] @@ -100889,7 +101150,7 @@ var ts; function tryUpdateExistingImport(context, importClause, importKind) { var symbolName = context.symbolName, sourceFile = context.sourceFile; var name = importClause.name; - var namedBindings = (importClause.kind !== 242 /* ImportEqualsDeclaration */ && importClause).namedBindings; + var namedBindings = (importClause.kind !== 242 /* ImportEqualsDeclaration */ && importClause).namedBindings; // TODO: GH#18217 switch (importKind) { case 1 /* Default */: return name ? undefined : ChangeTracker.with(context, function (t) { @@ -100935,11 +101196,6 @@ var ts; }); return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes); } - function getImportCodeActions(context) { - return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ? getActionsForUMDImport(context) - : getActionsForNonUMDImport(context); - } function getActionsForUMDImport(context) { var token = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); @@ -101001,7 +101257,14 @@ var ts; return undefined; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default"); - var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + var addToExistingDeclaration = []; + var addNewDeclaration = []; + getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).forEach(function (exportInfos) { + getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration); + }); + return addToExistingDeclaration.concat(addNewDeclaration); + } + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); @@ -101026,7 +101289,7 @@ var ts; addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); } function getEscapedNameForExportDefault(symbol) { - return ts.firstDefined(symbol.declarations, function (declaration) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { if (ts.isExportAssignment(declaration)) { if (ts.isIdentifier(declaration.expression)) { return declaration.expression.escapedText; @@ -101034,19 +101297,12 @@ var ts; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); - if (declaration.propertyName) { - return declaration.propertyName.escapedText; - } + return declaration.propertyName && declaration.propertyName.escapedText; } }); } }); - var addToExistingDeclaration = []; - var addNewDeclaration = []; - originalSymbolToExportInfos.forEach(function (exportInfos) { - getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration); - }); - return addToExistingDeclaration.concat(addNewDeclaration); + return originalSymbolToExportInfos; } function checkSymbolHasMeaning(_a, meaning) { var declarations = _a.declarations; @@ -101068,7 +101324,7 @@ var ts; for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { var sourceFile = allSourceFiles_1[_b]; if (ts.isExternalOrCommonJsModule(sourceFile)) { - cb(sourceFile.symbol, sourceFile); + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } @@ -101314,7 +101570,7 @@ var ts; if (token.parent.parent.kind === 199 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); // TODO: GH#18217 typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); @@ -101409,7 +101665,7 @@ var ts; var packageName = ts.getPackageName(moduleName).packageName; return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) - : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); + : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -101628,7 +101884,9 @@ var ts; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - doChange(changes, context.sourceFile, getInfo(diag.file, diag.start, diag.code)); + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); }); }, }); function getInfo(sourceFile, pos, diagCode) { @@ -101659,20 +101917,26 @@ var ts; ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { var errorCode = context.errorCode, sourceFile = context.sourceFile; - var importDecl = tryGetFullImport(sourceFile, context.span.start); + var startToken = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var importDecl = tryGetFullImport(startToken); if (importDecl) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } - var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start, /*deleted*/ undefined); }); + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, startToken, /*deleted*/ undefined); }); if (delDestructure.length) { return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(t, sourceFile, startToken, /*deleted*/ undefined); }); + if (delVar.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined); }); @@ -101688,9 +101952,10 @@ var ts; fixIds: [fixIdPrefix, fixIdDelete], getAllCodeActions: function (context) { // Track a set of deleted nodes that may be ancestors of other marked for deletion -- only delete the ancestors. - var deleted = new NodeSet(); + var deleted = new ts.NodeSet(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var sourceFile = context.sourceFile; + var startToken = ts.getTokenAtPosition(sourceFile, diag.start, /*includeJsDocComment*/ false); var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); switch (context.fixId) { case fixIdPrefix: @@ -101702,14 +101967,12 @@ var ts; // Ignore if this range was already deleted. if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); })) break; - var importDecl = tryGetFullImport(diag.file, diag.start); + var importDecl = tryGetFullImport(startToken); if (importDecl) { changes.deleteNode(sourceFile, importDecl); } - else { - if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) { - tryDeleteDeclaration(changes, sourceFile, token, deleted); - } + else if (!tryDeleteFullDestructure(changes, sourceFile, startToken, deleted) && !tryDeleteFullVariableStatement(changes, sourceFile, startToken, deleted)) { + tryDeleteDeclaration(changes, sourceFile, token, deleted); } break; default: @@ -101719,15 +101982,13 @@ var ts; }, }); // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. - function tryGetFullImport(sourceFile, pos) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + function tryGetFullImport(startToken) { return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; } - function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + function tryDeleteFullDestructure(changes, sourceFile, startToken, deletedAncestors) { if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent)) return false; - var decl = startToken.parent.parent; + var decl = ts.cast(startToken.parent, ts.isObjectBindingPattern).parent; switch (decl.kind) { case 231 /* VariableDeclaration */: tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors); @@ -101747,6 +102008,16 @@ var ts; } return true; } + function tryDeleteFullVariableStatement(changes, sourceFile, startToken, deletedAncestors) { + var declarationList = ts.tryCast(startToken.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === startToken) { + if (deletedAncestors) + deletedAncestors.add(declarationList); + changes.deleteNode(sourceFile, declarationList.parent.kind === 213 /* VariableStatement */ ? declarationList.parent : declarationList); + return true; + } + return false; + } function getToken(sourceFile, pos) { var token = ts.findPrecedingToken(pos, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); // this handles var ["computed"] = 12; @@ -101831,7 +102102,8 @@ var ts; // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + /*parameters*/ undefined, // TODO: GH#18217 + oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); // Drop leading and trailing trivia of the new function because we're only going // to replace the span (vs the full span) of the old function - the old leading // and trailing trivia will remain. @@ -101959,18 +102231,6 @@ var ts; } } } - var NodeSet = /** @class */ (function () { - function NodeSet() { - this.map = ts.createMap(); - } - NodeSet.prototype.add = function (node) { - this.map.set(String(ts.getNodeId(node)), node); - }; - NodeSet.prototype.some = function (pred) { - return ts.forEachEntry(this.map, pred) || false; - }; - return NodeSet; - }()); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -102034,6 +102294,8 @@ var ts; return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; case 237 /* EnumDeclaration */: return ts.hasModifier(s, 2048 /* Const */); + default: + return false; } } function sliceAfter(arr, value) { @@ -102120,7 +102382,7 @@ var ts; } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); @@ -102213,7 +102475,7 @@ var ts; default: return; } - return { + return insertBefore && { insertBefore: insertBefore, returnType: getReturnType(containingFunction) }; @@ -102508,7 +102770,7 @@ var ts; function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; + return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: @@ -102626,6 +102888,7 @@ var ts; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; }, reportInaccessibleThisError: notAccessible, @@ -102927,7 +103190,7 @@ var ts; return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { - var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); } @@ -102960,12 +103223,12 @@ var ts; } } if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); // TODO: GH#18217 } if (usageContext.stringIndexContext) { stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 } else { return undefined; @@ -103000,6 +103263,7 @@ var ts; parameters.push(symbol); } var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + // TODO: GH#18217 return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } function addCandidateType(context, type) { @@ -103008,7 +103272,7 @@ var ts; } } function hasCallContext(usageContext) { - return usageContext && usageContext.callContexts; + return !!usageContext && !!usageContext.callContexts; } })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); @@ -103041,7 +103305,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, context.preferences))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -103069,12 +103333,12 @@ var ts; return []; } var expr = node.expression; - var type = context.program.getTypeChecker().getTypeAtLocation(expr); + var type = context.program.getTypeChecker().getTypeAtLocation(expr); // TODO: GH#18217 if (!(type.symbol && type.symbol.originatingImport)) { return []; } var fixes = []; - var relatedImport = type.symbol.originatingImport; + var relatedImport = type.symbol.originatingImport; // TODO: GH#18217 if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } @@ -103151,8 +103415,9 @@ var ts; } 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)); + var type = propertyDeclaration.type; // TODO: GH#18217 + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); } function getActionForAddMissingInitializer(context, propertyDeclaration) { var checker = context.program.getTypeChecker(); @@ -103167,7 +103432,7 @@ var ts; changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { - return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 } function getDefaultValueFromType(checker, type) { if (type.flags & 2 /* String */) { @@ -103376,7 +103641,7 @@ var ts; // If the file is the main module, it can be imported by the package name var packageRootPath = path.substring(0, parts.packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { + if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); if (packageJsonContent) { var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; @@ -103461,7 +103726,7 @@ var ts; } function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } @@ -103527,14 +103792,14 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, 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); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { @@ -103550,8 +103815,8 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, preferences)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -103590,6 +103855,57 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + 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 token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var refactor; (function (refactor) { @@ -103672,7 +103988,7 @@ var ts; /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); - var targetRange = rangeToExtract.targetRange; + var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); if (parsedFunctionIndexMatch) { var index = +parsedFunctionIndexMatch[1]; @@ -103764,7 +104080,8 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; - for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { var errors_1 = checkNode(statement); @@ -103797,7 +104114,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -103897,6 +104214,9 @@ var ts; if (ts.isDeclaration(node)) { var declaringNode = (node.kind === 231 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { + // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) + // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! + // Also TODO: GH#19956 (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } @@ -103912,7 +104232,7 @@ var ts; // but a super *method call* simply implies a 'this' reference if (node.parent.kind === 186 /* CallExpression */) { // Super constructor call - var containingClass_1 = ts.getContainingClass(node); + var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; @@ -103923,7 +104243,7 @@ var ts; } break; } - if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { case 233 /* FunctionDeclaration */: case 234 /* ClassDeclaration */: @@ -104073,7 +104393,7 @@ var ts; function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - context.cancellationToken.throwIfCancellationRequested(); + context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217 return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { @@ -104170,7 +104490,7 @@ var ts; case 156 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: - ts.Debug.assertNever(scope); + throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { @@ -104238,7 +104558,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217 } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -104306,7 +104626,8 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), // TODO: GH#18217 + scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -104417,7 +104738,7 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -104433,7 +104754,7 @@ var ts; /*decorators*/ undefined, modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion - ? ts.createIdentifier(scope.name.getText()) + ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217 : ts.createThis(), ts.createIdentifier(localNameText)); // Declare var maxInsertionPos = node.pos; @@ -104527,7 +104848,7 @@ var ts; function getCalledExpression(scope, range, functionNameText) { var functionReference = ts.createIdentifier(functionNameText); if (ts.isClassLike(scope)) { - var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217 return ts.createPropertyAccess(lhs, functionReference); } else { @@ -104599,7 +104920,7 @@ var ts; } function getStatementsOrClassElements(scope) { if (ts.isFunctionLikeDeclaration(scope)) { - var body = scope.body; + var body = scope.body; // TODO: GH#18217 if (ts.isBlock(body)) { return body.statements; } @@ -104644,7 +104965,8 @@ var ts; } prevMember = member; } - ts.Debug.assert(prevMember !== undefined); // If the loop didn't return, then it did set prevMember. + if (prevMember === undefined) + return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember. return prevMember; } function getNodeToInsertConstantBefore(node, scope) { @@ -104671,18 +104993,15 @@ var ts; return curr.parent.parent; } // There must be at least one statement since we started in one. - ts.Debug.assert(prevStatement !== undefined); - return prevStatement; - } - if (curr === scope) { - ts.Debug.fail("Didn't encounter a block-like before encountering scope"); - break; + return ts.Debug.assertDefined(prevStatement); } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); } } function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + // TODO: GH#18217 `variableAssignments` not possibly undefined! return variableAssignments === undefined ? writeAssignments : writeAssignments === undefined @@ -104735,7 +105054,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { + else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { // TODO: GH#18217 expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -104768,7 +105087,7 @@ var ts; // will use the contextual type of an expression as the return type of the extracted // method (and will therefore "use" all the types involved). if (inGenericContext && !isReadonlyArray(targetRange.range)) { - var contextualType = checker.getContextualType(targetRange.range); + var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217 recordTypeParameterUsages(contextualType); } if (allTypeParameterUsages.size > 0) { @@ -104806,7 +105125,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_19 = function (i) { + var _loop_21 = 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 @@ -104846,7 +105165,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_19(i); + _loop_21(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -104868,7 +105187,7 @@ var ts; function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1 /* Read */; } if (inGenericContext) { - var type = checker.getTypeAtLocation(node); + var type = checker.getTypeAtLocation(node); // TODO: GH#18217 recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { @@ -105071,22 +105390,23 @@ var ts; * in the sense of something that you could extract on */ function isExtractableExpression(node) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 272 /* EnumMember */: return false; } switch (node.kind) { case 9 /* StringLiteral */: - return node.parent.kind !== 243 /* ImportDeclaration */ && - node.parent.kind !== 247 /* ImportSpecifier */; + return parent.kind !== 243 /* ImportDeclaration */ && + parent.kind !== 247 /* ImportSpecifier */; case 203 /* SpreadElement */: case 179 /* ObjectBindingPattern */: case 181 /* BindingElement */: return false; case 71 /* Identifier */: - return node.parent.kind !== 181 /* BindingElement */ && - node.parent.kind !== 247 /* ImportSpecifier */ && - node.parent.kind !== 251 /* ExportSpecifier */; + return parent.kind !== 181 /* BindingElement */ && + parent.kind !== 247 /* ImportSpecifier */ && + parent.kind !== 251 /* ExportSpecifier */; } return true; } @@ -105172,7 +105492,7 @@ var ts; var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } - function isConvertableName(name) { + function isConvertibleName(name) { return ts.isIdentifier(name) || ts.isStringLiteral(name); } function isAcceptedDeclaration(node) { @@ -105182,7 +105502,7 @@ var ts; return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name); } function createAccessorAccessExpression(fieldName, isStatic, container) { - var leftHead = isStatic ? container.name : ts.createThis(); + var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217 return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); } function getModifiers(isJS, isStatic, accessModifier) { @@ -105198,8 +105518,8 @@ var ts; var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; - if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) - || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) // TODO: GH#18217 + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; var name = declaration.name.text; var startWithUnderscore = startsWithUnderscore(name); @@ -105220,7 +105540,8 @@ var ts; function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { return ts.createGetAccessor( /*decorators*/ undefined, modifiers, accessorName, - /*parameters*/ undefined, type, ts.createBlock([ + /*parameters*/ undefined, // TODO: GH#18217 + type, ts.createBlock([ ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container)) ], /*multiLine*/ true)); } @@ -105264,7 +105585,9 @@ var ts; if (!constructor.body) return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; - var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); }); + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { + return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; var accessorName = ts.createIdentifier(fieldName.text); @@ -105287,7 +105610,7 @@ var ts; var refactorName = "Move to a new file"; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { - if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; @@ -105295,27 +105618,31 @@ var ts; getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === refactorName); var statements = ts.Debug.assertDefined(getStatementsToMove(context)); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - function getFirstAndLastStatementToMove(context) { + function getRangeToMove(context) { var file = context.file; var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); var statements = file.statements; var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); if (startNodeIndex === -1) return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return [statements[startNodeIndex]]; + } // Can't only partially include the start node or be partially into the next node - if (range.pos > statements[startNodeIndex].getStart(file)) + if (range.pos > startStatement.getStart(file)) return undefined; var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); // Can't be partially into the next node if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); } - function doChange(oldFile, program, toMove, changes, host) { + function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); @@ -105323,22 +105650,22 @@ var ts; var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. - changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); } // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. function getStatementsToMove(context) { - var statements = context.file.statements; - var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; var all = []; var ranges = []; - var rangeToMove = statements.slice(first, afterLast); ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { for (var i = start; i < afterEnd; i++) all.push(rangeToMove[i]); ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); }); - return { all: all, ranges: ranges }; + return all.length === 0 ? undefined : { all: all, ranges: ranges }; } function isPureImport(node) { switch (node.kind) { @@ -105347,7 +105674,7 @@ var ts; case 242 /* ImportEqualsDeclaration */: return !ts.hasModifier(node, 1 /* Export */); case 213 /* VariableStatement */: - return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; } @@ -105366,26 +105693,26 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { deleteMovedStatements(oldFile, toMove.ranges, changes); return toMove.all; } var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, preferences); if (importsFromNewFile) { changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); } function deleteMovedStatements(sourceFile, moved, changes) { for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { - var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last; - changes.deleteNodeRange(sourceFile, first_1, last_3); + var _a = moved_1[_i], first_1 = _a.first, last_2 = _a.last; + changes.deleteNodeRange(sourceFile, first_1, last_2); } } function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { @@ -105398,15 +105725,15 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_20 = function (sourceFile) { + var _loop_22 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_21 = function (statement) { + var _loop_23 = function (statement) { forEachImportInStatement(statement, function (importNode) { var shouldMove = function (name) { var symbol = ts.isBindingElement(name.parent) ? ts.getPropertySymbolFromBindingElement(checker, name.parent) - : ts.skipAlias(checker.getSymbolAtLocation(name), checker); + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217 return !!symbol && movedSymbols.has(symbol); }; deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file @@ -105418,12 +105745,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_21(statement); + _loop_23(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_20(sourceFile); + _loop_22(sourceFile); } } function moduleSpecifierFromImport(i) { @@ -105450,24 +105777,24 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { if (symbol.escapedName === "default" /* Default */) { - defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217 } else { imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { path = ts.ensurePathIsNonModuleName(path); if (useEs6Imports) { var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); - return ts.makeImportIfNecessary(defaultImport, specifiers, path); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, preferences); } else { ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. @@ -105566,7 +105893,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -105598,7 +105925,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -105606,7 +105933,7 @@ var ts; for (var i = 1;; i++) { var name = ts.combinePaths(inDirectory, newModuleName + extension); if (!host.fileExists(name)) - return newModuleName; + return newModuleName; // TODO: GH#18217 newModuleName = moduleName + "." + i; } } @@ -105857,7 +106184,7 @@ var ts; switch (decl.kind) { case 233 /* FunctionDeclaration */: case 234 /* ClassDeclaration */: - return [decl.name.text]; + return [decl.name.text]; // TODO: GH#18217 case 213 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); case 238 /* ModuleDeclaration */: @@ -105865,11 +106192,11 @@ var ts; case 236 /* TypeAliasDeclaration */: case 235 /* InterfaceDeclaration */: case 242 /* ImportEqualsDeclaration */: - return undefined; + return ts.emptyArray; case 215 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: - ts.Debug.assertNever(decl); + return ts.Debug.assertNever(decl); } } /** Creates `exports.x = x;` */ @@ -106089,7 +106416,7 @@ var ts; var value = 0; for (; moreDigits; state.decodingIndex++) { if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return; + return undefined; // TODO: GH#18217 } // 6 digit number var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); @@ -106139,7 +106466,7 @@ var ts; this.pos = pos; this.end = end; this.flags = 0 /* None */; - this.transformFlags = undefined; + this.transformFlags = undefined; // TODO: GH#18217 this.parent = undefined; this.kind = kind; } @@ -106325,7 +106652,7 @@ var ts; return 0; }; TokenOrIdentifierObject.prototype.getChildAt = function () { - return undefined; + return undefined; // TODO: GH#18217 }; TokenOrIdentifierObject.prototype.getChildren = function () { return ts.emptyArray; @@ -106517,9 +106844,9 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); @@ -106823,7 +107150,7 @@ var ts; }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; + return ts.isString(info) ? undefined : info; // TODO: GH#18217 }; HostCache.prototype.getRootFileNames = function () { var names = []; @@ -106841,11 +107168,11 @@ var ts; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); - return file && file.version; + return (file && file.version); // TODO: GH#18217 }; HostCache.prototype.getScriptSnapshot = function (path) { var file = this.getHostFileInformation(path); - return file && file.scriptSnapshot; + return (file && file.scriptSnapshot); // TODO: GH#18217 }; return HostCache; }()); @@ -106948,7 +107275,7 @@ var ts; this.cancellationToken = cancellationToken; } CancellationTokenObject.prototype.isCancellationRequested = function () { - return this.cancellationToken && this.cancellationToken.isCancellationRequested(); + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { @@ -106998,7 +107325,7 @@ var ts; if (!host.fileExists || !host.readFile || !host.fileExists(path)) return; // And failing that, check the disk - var text = host.readFile(path); + var text = host.readFile(path); // TODO: GH#18217 var file = { text: text, lineMap: undefined, @@ -107056,7 +107383,7 @@ var ts; var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; if (lastTypesRootVersion !== typeRootsVersion) { log("TypeRoots version has changed; provide new program"); - program = undefined; + program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } // Get a fresh cache of the host information @@ -107064,7 +107391,7 @@ var ts; var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -107141,7 +107468,7 @@ var ts; var entry = hostCache.getEntryByPath(path); return entry ? !ts.isString(entry) : - (host.fileExists && host.fileExists(fileName)); + (!!host.fileExists && host.fileExists(fileName)); } // Release any files we have acquired in the old program but are // not part of the new program. @@ -107201,6 +107528,7 @@ var ts; return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } + // TODO: GH#18217 frequently asserted as defined function getProgram() { if (syntaxOnly) { ts.Debug.assert(program === undefined); @@ -107210,14 +107538,14 @@ var ts; return program; } function cleanupSemanticCache() { - program = undefined; + program = undefined; // TODO: GH#18217 } function dispose() { if (program) { ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); - program = undefined; + program = undefined; // TODO: GH#18217 } host = undefined; } @@ -107261,7 +107589,8 @@ var ts; function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName, preferences, cancellationToken); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + getCanonicalFileName, preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -107330,7 +107659,7 @@ var ts; } function toLineColumnOffset(fileName, position) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); + var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) @@ -107397,7 +107726,7 @@ var ts; var location = possibleMapLocations_1[_i]; var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 } } return file.sourceMapper = ts.sourcemaps.identitySourceMapper; @@ -107529,11 +107858,13 @@ var ts; } /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); @@ -107560,7 +107891,7 @@ var ts; // Get node at the location var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { - return; + return undefined; } switch (node.kind) { case 184 /* PropertyAccessExpression */: @@ -107576,7 +107907,7 @@ var ts; break; // Cant create the text span default: - return; + return undefined; } var nodeForStartPos = node; while (true) { @@ -107739,7 +108070,7 @@ var ts; ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); default: - ts.Debug.fail(); + return ts.Debug.fail(); // TODO: Debug.assertNever(action); will only work if there is more than one type. } } @@ -107830,7 +108161,8 @@ var ts; descriptor = descriptors[i]; } } - ts.Debug.assert(descriptor !== undefined); + if (descriptor === undefined) + return ts.Debug.fail(); // We don't want to match something like 'TODOBY', so we make sure a non // letter/digit follows the match. if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { @@ -107995,7 +108327,7 @@ var ts; if (!sourceFile.nameTable) { initializeNameTable(sourceFile); } - return sourceFile.nameTable; + return sourceFile.nameTable; // TODO: GH#18217 } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { @@ -108049,8 +108381,8 @@ var ts; /* @internal */ function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); - return getPropertySymbolsFromType(contextualType, node.name); + var contextualType = typeChecker.getContextualType(objectLiteral); // TODO: GH#18217 + return getPropertySymbolsFromType(contextualType, node.name); // TODO: GH#18217 } ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; /* @internal */ @@ -108118,11 +108450,12 @@ var ts; // let y = 10; // token at position will return let keyword on second line as the token but we would like to use // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line - tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); // It's a blank line - if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { return undefined; } + tokenAtLocation = preceding; } // Cannot set breakpoint in ambient declarations if (tokenAtLocation.flags & 4194304 /* Ambient */) { @@ -108156,6 +108489,7 @@ var ts; } function spanInNode(node) { if (node) { + var parent = node.parent; switch (node.kind) { case 213 /* VariableStatement */: // Span on first variable declaration @@ -108258,7 +108592,7 @@ var ts; // span in statement return spanInNode(node.statement); case 149 /* Decorator */: - return spanInNodeArray(node.parent.decorators); + return spanInNodeArray(parent.decorators); case 179 /* ObjectBindingPattern */: case 180 /* ArrayBindingPattern */: return spanInBindingPattern(node); @@ -108310,7 +108644,7 @@ var ts; node.kind === 203 /* SpreadElement */ || node.kind === 269 /* PropertyAssignment */ || node.kind === 270 /* ShorthandPropertyAssignment */) && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } if (node.kind === 199 /* BinaryExpression */) { @@ -108334,7 +108668,7 @@ var ts; } } if (ts.isExpressionNode(node)) { - switch (node.parent.kind) { + switch (parent.kind) { case 217 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); @@ -108414,6 +108748,7 @@ var ts; if (variableDeclaration.parent.parent.kind === 220 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } + var parent = variableDeclaration.parent; // If this is a destructuring pattern, set breakpoint in binding pattern if (ts.isBindingPattern(variableDeclaration.name)) { return spanInBindingPattern(variableDeclaration.name); @@ -108422,7 +108757,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - variableDeclaration.parent.parent.kind === 221 /* ForOfStatement */) { + parent.parent.kind === 221 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -108709,7 +109044,7 @@ var ts; */ function transform(source, transformers, compilerOptions) { var diagnostics = []; - compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); + compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217 var nodes = ts.isArray(source) ? source : [source]; var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); @@ -108758,16 +109093,16 @@ var ts; var oldSnapshotShim = oldSnapshot; var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); if (encoded === null) { - return null; + return null; // TODO: GH#18217 } - var decoded = JSON.parse(encoded); + var decoded = JSON.parse(encoded); // TODO: GH#18217 return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; ScriptSnapshotShimAdapter.prototype.dispose = function () { // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments // 'in' does not have this effect if ("dispose" in this.scriptSnapshotShim) { - this.scriptSnapshotShim.dispose(); + this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`? } }; return ScriptSnapshotShimAdapter; @@ -108782,10 +109117,10 @@ var ts; // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { this.resolveModuleNames = function (moduleNames, containingFile) { - var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217 }); }; } @@ -108794,8 +109129,8 @@ var ts; } if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217 }; } } @@ -108815,7 +109150,7 @@ var ts; LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { if (!this.shimHost.getProjectVersion) { // shimmed host does not support getProjectVersion - return undefined; + return undefined; // TODO: GH#18217 } return this.shimHost.getProjectVersion(); }; @@ -108848,7 +109183,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { if ("getScriptKind" in this.shimHost) { - return this.shimHost.getScriptKind(fileName); + return this.shimHost.getScriptKind(fileName); // TODO: GH#18217 } else { return 0 /* Unknown */; @@ -108884,7 +109219,7 @@ var ts; return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { @@ -108905,11 +109240,11 @@ var ts; this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } if ("realpath" in this.shimHost) { - this.realpath = function (path) { return _this.shimHost.realpath(path); }; + this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -108981,7 +109316,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = /** @class */ (function (_super) { @@ -109287,10 +109623,12 @@ var ts; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); var result = ""; for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index d237cc98eee..045c59c9b42 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -460,7 +460,7 @@ declare namespace ts { flags: NodeFlags; decorators?: NodeArray; modifiers?: ModifiersArray; - parent?: Node; + parent: Node; } interface JSDocContainer { } @@ -525,12 +525,12 @@ declare namespace ts { } interface Decorator extends Node { kind: SyntaxKind.Decorator; - parent?: NamedDeclaration; + parent: NamedDeclaration; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; - parent?: DeclarationWithTypeParameters | InferTypeNode; + parent: DeclarationWithTypeParameters | InferTypeNode; name: Identifier; constraint?: TypeNode; default?: TypeNode; @@ -541,7 +541,7 @@ declare namespace ts { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; - type: TypeNode | undefined; + type?: TypeNode; } type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { @@ -553,7 +553,7 @@ declare namespace ts { type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; - parent?: VariableDeclarationList | CatchClause; + parent: VariableDeclarationList | CatchClause; name: BindingName; exclamationToken?: ExclamationToken; type?: TypeNode; @@ -561,12 +561,12 @@ declare namespace ts { } interface VariableDeclarationList extends Node { kind: SyntaxKind.VariableDeclarationList; - parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; + parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.Parameter; - parent?: SignatureDeclaration; + parent: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; name: BindingName; questionToken?: QuestionToken; @@ -575,7 +575,7 @@ declare namespace ts { } interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; - parent?: BindingPattern; + parent: BindingPattern; propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: BindingName; @@ -628,12 +628,12 @@ declare namespace ts { } interface ObjectBindingPattern extends Node { kind: SyntaxKind.ObjectBindingPattern; - parent?: VariableDeclaration | ParameterDeclaration | BindingElement; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; elements: NodeArray; } interface ArrayBindingPattern extends Node { kind: SyntaxKind.ArrayBindingPattern; - parent?: VariableDeclaration | ParameterDeclaration | BindingElement; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; elements: NodeArray; } type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; @@ -662,41 +662,41 @@ declare namespace ts { } interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; - parent?: ObjectTypeDeclaration; + parent: ObjectTypeDeclaration; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.MethodDeclaration; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassLikeDeclaration; + parent: ClassLikeDeclaration; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassLikeDeclaration; + parent: ClassLikeDeclaration; } interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ObjectTypeDeclaration; + parent: ObjectTypeDeclaration; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -730,7 +730,7 @@ declare namespace ts { } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; - parent?: SignatureDeclaration; + parent: SignatureDeclaration; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -959,15 +959,15 @@ declare namespace ts { } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; - parent?: TemplateExpression; + parent: TemplateExpression; } interface TemplateMiddle extends LiteralLikeNode { kind: SyntaxKind.TemplateMiddle; - parent?: TemplateSpan; + parent: TemplateSpan; } interface TemplateTail extends LiteralLikeNode { kind: SyntaxKind.TemplateTail; - parent?: TemplateSpan; + parent: TemplateSpan; } type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { @@ -977,7 +977,7 @@ declare namespace ts { } interface TemplateSpan extends Node { kind: SyntaxKind.TemplateSpan; - parent?: TemplateExpression; + parent: TemplateExpression; expression: Expression; literal: TemplateMiddle | TemplateTail; } @@ -991,7 +991,7 @@ declare namespace ts { } interface SpreadElement extends Expression { kind: SyntaxKind.SpreadElement; - parent?: ArrayLiteralExpression | CallExpression | NewExpression; + parent: ArrayLiteralExpression | CallExpression | NewExpression; expression: Expression; } /** @@ -1044,7 +1044,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent?: HeritageClause; + parent: HeritageClause; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1090,11 +1090,11 @@ declare namespace ts { type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxAttributes extends ObjectLiteralExpressionBase { - parent?: JsxOpeningLikeElement; + parent: JsxOpeningLikeElement; } interface JsxOpeningElement extends Expression { kind: SyntaxKind.JsxOpeningElement; - parent?: JsxElement; + parent: JsxElement; tagName: JsxTagNameExpression; typeArguments?: NodeArray; attributes: JsxAttributes; @@ -1113,38 +1113,38 @@ declare namespace ts { } interface JsxOpeningFragment extends Expression { kind: SyntaxKind.JsxOpeningFragment; - parent?: JsxFragment; + parent: JsxFragment; } interface JsxClosingFragment extends Expression { kind: SyntaxKind.JsxClosingFragment; - parent?: JsxFragment; + parent: JsxFragment; } interface JsxAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxAttribute; - parent?: JsxAttributes; + parent: JsxAttributes; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxSpreadAttribute; - parent?: JsxAttributes; + parent: JsxAttributes; expression: Expression; } interface JsxClosingElement extends Node { kind: SyntaxKind.JsxClosingElement; - parent?: JsxElement; + parent: JsxElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { kind: SyntaxKind.JsxExpression; - parent?: JsxElement | JsxAttributeLike; + parent: JsxElement | JsxAttributeLike; dotDotDotToken?: Token; expression?: Expression; } interface JsxText extends Node { kind: SyntaxKind.JsxText; containsOnlyWhiteSpaces: boolean; - parent?: JsxElement; + parent: JsxElement; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; interface Statement extends Node { @@ -1245,18 +1245,18 @@ declare namespace ts { } interface CaseBlock extends Node { kind: SyntaxKind.CaseBlock; - parent?: SwitchStatement; + parent: SwitchStatement; clauses: NodeArray; } interface CaseClause extends Node { kind: SyntaxKind.CaseClause; - parent?: CaseBlock; + parent: CaseBlock; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { kind: SyntaxKind.DefaultClause; - parent?: CaseBlock; + parent: CaseBlock; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; @@ -1267,7 +1267,7 @@ declare namespace ts { } interface ThrowStatement extends Statement { kind: SyntaxKind.ThrowStatement; - expression: Expression; + expression?: Expression; } interface TryStatement extends Statement { kind: SyntaxKind.TryStatement; @@ -1277,7 +1277,7 @@ declare namespace ts { } interface CatchClause extends Node { kind: SyntaxKind.CatchClause; - parent?: TryStatement; + parent: TryStatement; variableDeclaration?: VariableDeclaration; block: Block; } @@ -1317,7 +1317,7 @@ declare namespace ts { } interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassLikeDeclaration; + parent: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -1329,7 +1329,7 @@ declare namespace ts { } interface EnumMember extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.EnumMember; - parent?: EnumDeclaration; + parent: EnumDeclaration; name: PropertyName; initializer?: Expression; } @@ -1342,7 +1342,7 @@ declare namespace ts { type ModuleBody = NamespaceBody | JSDocNamespaceBody; interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ModuleDeclaration; - parent?: ModuleBody | SourceFile; + parent: ModuleBody | SourceFile; name: ModuleName; body?: ModuleBody | JSDocNamespaceDeclaration; } @@ -1354,11 +1354,11 @@ declare namespace ts { type JSDocNamespaceBody = Identifier | JSDocNamespaceDeclaration; interface JSDocNamespaceDeclaration extends ModuleDeclaration { name: Identifier; - body: JSDocNamespaceBody; + body?: JSDocNamespaceBody; } interface ModuleBlock extends Node, Statement { kind: SyntaxKind.ModuleBlock; - parent?: ModuleDeclaration; + parent: ModuleDeclaration; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; @@ -1369,18 +1369,18 @@ declare namespace ts { */ interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ImportEqualsDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { kind: SyntaxKind.ExternalModuleReference; - parent?: ImportEqualsDeclaration; - expression?: Expression; + parent: ImportEqualsDeclaration; + expression: Expression; } interface ImportDeclaration extends Statement { kind: SyntaxKind.ImportDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; importClause?: ImportClause; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier: Expression; @@ -1388,13 +1388,13 @@ declare namespace ts { type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; - parent?: ImportDeclaration; + parent: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; - parent?: ImportClause; + parent: ImportClause; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { @@ -1403,7 +1403,7 @@ declare namespace ts { } interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ @@ -1411,24 +1411,24 @@ declare namespace ts { } interface NamedImports extends Node { kind: SyntaxKind.NamedImports; - parent?: ImportClause; + parent: ImportClause; elements: NodeArray; } interface NamedExports extends Node { kind: SyntaxKind.NamedExports; - parent?: ExportDeclaration; + parent: ExportDeclaration; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; - parent?: NamedImports; + parent: NamedImports; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; - parent?: NamedExports; + parent: NamedExports; propertyName?: Identifier; name: Identifier; } @@ -1439,7 +1439,7 @@ declare namespace ts { */ interface ExportAssignment extends DeclarationStatement { kind: SyntaxKind.ExportAssignment; - parent?: SourceFile; + parent: SourceFile; isExportEquals?: boolean; expression: Expression; } @@ -1494,15 +1494,15 @@ declare namespace ts { type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; - parent?: HasJSDoc; - tags: NodeArray | undefined; - comment: string | undefined; + parent: HasJSDoc; + tags?: NodeArray; + comment?: string; } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; atToken: AtToken; tagName: Identifier; - comment: string | undefined; + comment?: string; } interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; @@ -1526,11 +1526,11 @@ declare namespace ts { } interface JSDocReturnTag extends JSDocTag { kind: SyntaxKind.JSDocReturnTag; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { kind: SyntaxKind.JSDocTypeTag; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { parent: JSDoc; @@ -1608,7 +1608,7 @@ declare namespace ts { container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNodeBase { - antecedents: FlowNode[]; + antecedents: FlowNode[] | undefined; } interface FlowAssignment extends FlowNodeBase { node: Expression | VariableDeclaration | BindingElement; @@ -1635,7 +1635,7 @@ declare namespace ts { } interface AmdDependency { path: string; - name: string; + name?: string; } interface SourceFile extends Declaration { kind: SyntaxKind.SourceFile; @@ -1644,7 +1644,7 @@ declare namespace ts { fileName: string; text: string; amdDependencies: ReadonlyArray; - moduleName: string; + moduleName?: string; referencedFiles: ReadonlyArray; typeReferenceDirectives: ReadonlyArray; languageVariant: LanguageVariant; @@ -1704,7 +1704,7 @@ declare namespace ts { fileExists(path: string): boolean; readFile(path: string): string | undefined; } - type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray) => void; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { @@ -1734,9 +1734,10 @@ declare namespace ts { emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. @@ -1793,7 +1794,7 @@ declare namespace ts { emitSkipped: boolean; /** Contains declaration emit diagnostics */ diagnostics: ReadonlyArray; - emittedFiles: string[]; + emittedFiles?: string[]; } interface TypeChecker { getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; @@ -1810,7 +1811,7 @@ declare namespace ts { getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; + typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; @@ -1846,7 +1847,7 @@ declare namespace ts { */ getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; - getTypeAtLocation(node: Node): Type; + getTypeAtLocation(node: Node): Type | undefined; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; @@ -1863,9 +1864,10 @@ declare namespace ts { getContextualType(node: Expression): Type | undefined; /** * returns unknownSignature in the case of an error. + * returns undefined if the node is not valid. * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. */ - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; @@ -2069,8 +2071,8 @@ declare namespace ts { interface Symbol { flags: SymbolFlags; escapedName: __String; - declarations?: Declaration[]; - valueDeclaration?: Declaration; + declarations: Declaration[]; + valueDeclaration: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; @@ -2172,15 +2174,15 @@ declare namespace ts { type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { flags: TypeFlags; - symbol?: Symbol; + symbol: Symbol; pattern?: DestructuringPattern; aliasSymbol?: Symbol; aliasTypeArguments?: Type[]; } interface LiteralType extends Type { value: string | number; - freshType?: LiteralType; - regularType?: LiteralType; + freshType: LiteralType; + regularType: LiteralType; } interface UniqueESSymbolType extends Type { symbol: Symbol; @@ -2215,18 +2217,18 @@ declare namespace ts { } /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[]; - outerTypeParameters: TypeParameter[]; - localTypeParameters: TypeParameter[]; - thisType: TypeParameter; + typeParameters: TypeParameter[] | undefined; + outerTypeParameters: TypeParameter[] | undefined; + localTypeParameters: TypeParameter[] | undefined; + thisType: TypeParameter | undefined; } type BaseType = ObjectType | IntersectionType; interface InterfaceTypeWithDeclaredMembers extends InterfaceType { declaredProperties: Symbol[]; declaredCallSignatures: Signature[]; declaredConstructSignatures: Signature[]; - declaredStringIndexInfo: IndexInfo; - declaredNumberIndexInfo: IndexInfo; + declaredStringIndexInfo?: IndexInfo; + declaredNumberIndexInfo?: IndexInfo; } /** * Type references (ObjectFlags.Reference). When a class or interface has type parameters or @@ -2277,11 +2279,11 @@ declare namespace ts { trueType: Type; falseType: Type; isDistributive: boolean; - inferTypeParameters: TypeParameter[]; + inferTypeParameters?: TypeParameter[]; outerTypeParameters?: TypeParameter[]; instantiations?: Map; - aliasSymbol: Symbol; - aliasTypeArguments: Type[]; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; } interface ConditionalType extends InstantiableType { root: ConditionalRoot; @@ -2359,6 +2361,11 @@ declare namespace ts { code: number; source?: string; } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; + } enum DiagnosticCategory { Warning = 0, Error = 1, @@ -2447,6 +2454,7 @@ declare namespace ts { sourceMap?: boolean; sourceRoot?: string; strict?: boolean; + strictAny?: boolean; strictFunctionTypes?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; @@ -2624,7 +2632,7 @@ declare namespace ts { packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { - readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; readonly failedLookupLocations: ReadonlyArray; } interface CompilerHost extends ModuleResolutionHost { @@ -2644,8 +2652,8 @@ declare namespace ts { /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; - getEnvironmentVariable?(name: string): string; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; } interface SourceMapRange extends TextRange { @@ -2657,6 +2665,7 @@ declare namespace ts { skipTrivia?: (pos: number) => number; } enum EmitFlags { + None = 0, SingleLine = 1, AdviseOnEmitNode = 2, NoSubstitution = 4, @@ -2710,7 +2719,7 @@ declare namespace ts { /** Resumes a suspended lexical environment, usually before visiting a function body. */ resumeLexicalEnvironment(): void; /** Ends a lexical environment, returning any declarations. */ - endLexicalEnvironment(): Statement[]; + endLexicalEnvironment(): Statement[] | undefined; /** Hoists a function declaration to the containing scope. */ hoistFunctionDeclaration(node: FunctionDeclaration): void; /** Hoists a variable declaration to the containing scope. */ @@ -2754,7 +2763,7 @@ declare namespace ts { /** Gets the transformed source files. */ transformed: T[]; /** Gets diagnostics for the transformation. */ - diagnostics?: Diagnostic[]; + diagnostics?: DiagnosticWithLocation[]; /** * Gets a substitute for a node, if one is available; otherwise, returns the original node. * @@ -2841,7 +2850,7 @@ declare namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -2954,13 +2963,13 @@ declare namespace ts { } } declare namespace ts { - const versionMajorMinor = "2.9"; + const versionMajorMinor = "3.0"; /** The version of the TypeScript compiler release */ const version: string; } declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): Diagnostic[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3014,7 +3023,7 @@ declare namespace ts { interface FileWatcher { close(): void; } - function getNodeMajorVersion(): number; + function getNodeMajorVersion(): number | undefined; let sys: System; } declare namespace ts { @@ -3041,8 +3050,8 @@ declare namespace ts { scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; - setText(text: string, start?: number, length?: number): void; - setOnError(onError: ErrorCallback): void; + setText(text: string | undefined, start?: number, length?: number): void; + setOnError(onError: ErrorCallback | undefined): void; setScriptTarget(scriptTarget: ScriptTarget): void; setLanguageVariant(variant: LanguageVariant): void; setTextPos(textPos: number): void; @@ -3062,15 +3071,15 @@ declare namespace ts { function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; - function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; - function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ function getShebang(text: string): string | undefined; - function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -3079,12 +3088,12 @@ declare namespace ts { function textSpanContainsPosition(span: TextSpan, position: number): boolean; function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined; function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined; function createTextSpan(start: number, length: number): TextSpan; function createTextSpanFromBounds(start: number, end: number): TextSpan; function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; @@ -3100,7 +3109,7 @@ declare namespace ts { * Vn. */ function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration; + function getTypeParameterOwner(d: Declaration): Declaration | undefined; type ParameterPropertyDeclaration = ParameterDeclaration & { parent: ConstructorDeclaration; name: Identifier; @@ -3122,6 +3131,8 @@ declare namespace ts { }, errors?: Push): void; function getOriginalNode(node: Node): Node; function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + function getOriginalNode(node: Node | undefined): Node | undefined; + function getOriginalNode(node: Node | undefined, nodeTest: (node: Node | undefined) => node is T): T | undefined; /** * Gets a value indicating whether a node originated in the parse tree. * @@ -3142,7 +3153,7 @@ declare namespace ts { * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. * @returns The original parse tree node if found; otherwise, undefined. */ - function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; + function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; /** * Remove extra underscore from escaped identifier text content. * @@ -3160,7 +3171,7 @@ declare namespace ts { */ function unescapeIdentifier(id: string): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; - function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName; /** * Gets the JSDoc parameter tags for the node if present. * @@ -3442,7 +3453,7 @@ declare namespace ts { */ function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; - function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined; /** * Parse json text into SyntaxTree and return node and parse errors if any * @param fileName @@ -3488,7 +3499,7 @@ declare namespace ts { getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; } interface PerModuleNameCache { - get(directory: string): ResolvedModuleWithFailedLookupLocations; + get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; @@ -3570,7 +3581,7 @@ declare namespace ts { function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; function createTypeQueryNode(exprName: EntityName): TypeQueryNode; function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createTypeLiteralNode(members: ReadonlyArray): TypeLiteralNode; + function createTypeLiteralNode(members: ReadonlyArray | undefined): TypeLiteralNode; function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; @@ -3609,23 +3620,23 @@ declare namespace ts { function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; - function createPropertyAccess(expression: Expression, name: string | Identifier): PropertyAccessExpression; + function createPropertyAccess(expression: Expression, name: string | Identifier | undefined): PropertyAccessExpression; function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; - function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): CallExpression; function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; - function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray, template: TemplateLiteral): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; - function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray, template: TemplateLiteral): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; function createParen(expression: Expression): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; @@ -3655,15 +3666,15 @@ declare namespace ts { function createTemplateTail(text: string): TemplateTail; function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; function createYield(expression?: Expression): YieldExpression; - function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; + function createYield(asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function createSpread(expression: Expression): SpreadElement; function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; - function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; - function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; function createOmittedExpression(): OmittedExpression; - function createExpressionWithTypeArguments(typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; - function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; function createAsExpression(expression: Expression, type: TypeNode): AsExpression; function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; @@ -3690,8 +3701,8 @@ declare namespace ts { function updateFor(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - function createForOf(awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; - function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createForOf(awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; function createContinue(label?: string | Identifier): ContinueStatement; function updateContinue(node: ContinueStatement, label: Identifier | undefined): ContinueStatement; function createBreak(label?: string | Identifier): BreakStatement; @@ -3715,8 +3726,8 @@ declare namespace ts { function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; - function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; @@ -3734,7 +3745,7 @@ declare namespace ts { function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; - function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function createNamespaceImport(name: Identifier): NamespaceImport; @@ -3743,7 +3754,7 @@ declare namespace ts { function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; @@ -3873,16 +3884,16 @@ declare namespace ts { */ function setCommentRange(node: T, range: TextRange): T; function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[]): T; + function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T; function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; + function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; function moveSyntheticComments(node: T, original: Node): T; /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number | undefined; /** * Sets the constant value to emit for an expression. */ @@ -3918,7 +3929,7 @@ declare namespace ts { * @param test A callback to execute to verify the Node is valid. * @param lift An optional callback to execute to lift a NodeArray into a valid Node. */ - function visitNode(node: T, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; /** * Visits a Node using the supplied visitor, possibly returning a new Node in its place. * @@ -3927,7 +3938,7 @@ declare namespace ts { * @param test A callback to execute to verify the Node is valid. * @param lift An optional callback to execute to lift a NodeArray into a valid Node. */ - function visitNode(node: T | undefined, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; /** * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. * @@ -3937,7 +3948,7 @@ declare namespace ts { * @param start An optional value indicating the starting offset at which to start visiting. * @param count An optional value indicating the maximum number of nodes to visit. */ - function visitNodes(nodes: NodeArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; /** * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. * @@ -3957,7 +3968,7 @@ declare namespace ts { * Starts a new lexical environment and visits a parameter list, suspending the lexical * environment upon completion. */ - function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; /** * Resumes a suspended lexical environment and visits a function body, ending the lexical * environment and merging hoisted declarations upon completion. @@ -4006,7 +4017,7 @@ declare namespace ts { function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string; function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' @@ -4201,11 +4212,11 @@ declare namespace ts { /** If provided would be used to write log about compilation */ trace?(s: string): void; /** If provided is used to get the environment variable */ - getEnvironmentVariable?(name: string): string; + getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; /** Used to watch changes in source files, missing files needed to update the program or config file */ watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ @@ -4355,8 +4366,8 @@ declare namespace ts { getLeadingTriviaWidth(sourceFile?: SourceFile): number; getFullText(sourceFile?: SourceFile): string; getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node; - getLastToken(sourceFile?: SourceFile): Node; + getFirstToken(sourceFile?: SourceFile): Node | undefined; + getLastToken(sourceFile?: SourceFile): Node | undefined; forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; } interface Identifier { @@ -4444,7 +4455,7 @@ declare namespace ts { referencedFiles: FileReference[]; typeReferenceDirectives: FileReference[]; importedFiles: FileReference[]; - ambientExternalModules: string[]; + ambientExternalModules?: string[]; isLibFile: boolean; } interface HostCancellationToken { @@ -4477,7 +4488,7 @@ declare namespace ts { fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; - getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getDirectories?(directoryName: string): string[]; /** @@ -4497,9 +4508,10 @@ declare namespace ts { } interface LanguageService { cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(fileName: string): Diagnostic[]; - getSuggestionDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. @@ -4511,24 +4523,24 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails; - getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol; - getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; - getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; + getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; - getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - findReferences(fileName: string, position: number): ReferencedSymbol[]; - getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; @@ -4539,9 +4551,9 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan | undefined; toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; @@ -4559,7 +4571,7 @@ declare namespace ts { organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; - getProgram(): Program; + getProgram(): Program | undefined; dispose(): void; } interface CombinedCodeFixScope { @@ -4662,7 +4674,7 @@ declare namespace ts { } interface CombinedCodeActions { changes: ReadonlyArray; - commands: ReadonlyArray | undefined; + commands?: ReadonlyArray; } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { @@ -4712,8 +4724,8 @@ declare namespace ts { */ interface RefactorEditInfo { edits: FileTextChanges[]; - renameFilename: string | undefined; - renameLocation: number | undefined; + renameFilename?: string; + renameLocation?: number; commands?: CodeActionCommand[]; } interface TextInsertion { @@ -4834,7 +4846,7 @@ declare namespace ts { containerName: string; } interface DefinitionInfoAndBoundSpan { - definitions: ReadonlyArray; + definitions?: ReadonlyArray; textSpan: TextSpan; } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { @@ -4880,13 +4892,13 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; textSpan: TextSpan; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - tags: JSDocTagInfo[]; + displayParts?: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; } interface RenameInfo { canRename: boolean; - localizedErrorMessage: string; + localizedErrorMessage?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; @@ -4938,7 +4950,7 @@ declare namespace ts { interface CompletionEntry { name: string; kind: ScriptElementKind; - kindModifiers: string; + kindModifiers?: string; sortText: string; insertText?: string; /** @@ -4956,8 +4968,8 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - tags: JSDocTagInfo[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; source?: SymbolDisplayPart[]; } @@ -5270,12 +5282,12 @@ declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string; function getDefaultCompilerOptions(): CompilerOptions; function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; - function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnly?: boolean): LanguageService; /** * Get the path of the default library files (lib.d.ts) as distributed with the typescript diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 5a20323ef59..01ebe51383d 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -1325,6 +1325,7 @@ var ts; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; @@ -1633,7 +1634,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "2.9"; + ts.versionMajorMinor = "3.0"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1937,7 +1938,7 @@ var ts; return result; } } - Debug.fail(); + return Debug.fail(); } ts.findMap = findMap; function contains(array, value, equalityComparer) { @@ -2055,11 +2056,6 @@ var ts; return array; } ts.sameMap = sameMap; - /** - * Flattens an array containing a mix of array or non-array elements. - * - * @param array The array to flatten. - */ function flatten(array) { var result; if (array) { @@ -2079,12 +2075,6 @@ var ts; return result; } ts.flatten = flatten; - /** - * Maps an array. If the mapped value is an array, it is spread into the result. - * - * @param array The array to map. - * @param mapfn The callback used to map the result into one or more values. - */ function flatMap(array, mapfn) { var result; if (array) { @@ -2207,13 +2197,6 @@ var ts; }; } ts.singleIterator = singleIterator; - /** - * Maps contiguous spans of values with the same key. - * - * @param array The array to map. - * @param keyfn A callback used to select the key for an element. - * @param mapfn A callback used to map a contiguous chunk of values to a single value. - */ function spanMap(array, keyfn, mapfn) { var result; if (array) { @@ -2331,12 +2314,6 @@ var ts; } return result; } - /** - * Deduplicates an unsorted array. - * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. - * @param comparer An optional `Comparer` used to sort entries before comparison, though the - * result will remain in the original order in `array`. - */ function deduplicate(array, equalityComparer, comparer) { return !array ? undefined : array.length === 0 ? [] : @@ -2345,9 +2322,6 @@ var ts; deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; - /** - * Deduplicates an array that has already been sorted. - */ function deduplicateSorted(array, comparer) { if (!array) return undefined; @@ -2490,14 +2464,6 @@ var ts; return result; } ts.sum = sum; - /** - * Appends a value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param value The value to append to the array. If `value` is `undefined`, nothing is - * appended. - */ function append(to, value) { if (value === undefined) return to; @@ -2514,16 +2480,6 @@ var ts; function toOffset(array, offset) { return offset < 0 ? array.length + offset : offset; } - /** - * Appends a range of value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - * @param start The offset in `from` at which to start copying values. - * @param end The offset in `from` at which to stop copying values (non-inclusive). - */ function addRange(to, from, start, end) { if (from === undefined || from.length === 0) return to; @@ -2539,23 +2495,6 @@ var ts; return to; } ts.addRange = addRange; - /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - */ - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; /** * @return Whether the value was added. */ @@ -2853,7 +2792,7 @@ var ts; var arg = args_1[_a]; for (var p in arg) { if (hasProperty(arg, p)) { - t[p] = arg[p]; + t[p] = arg[p]; // TODO: GH#23368 } } } @@ -3012,10 +2951,10 @@ var ts; if (value !== undefined && test(value)) return value; if (value && typeof value.kind === "number") { - Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); } else { - Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } } ts.cast = cast; @@ -3101,7 +3040,7 @@ var ts; } ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { - baseIndex = baseIndex || 0; + if (baseIndex === void 0) { baseIndex = 0; } return text.replace(/{(\d+)}/g, function (_match, index) { return Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; @@ -3409,7 +3348,9 @@ var ts; return compareValues(a ? 1 : 0, b ? 1 : 0); } ts.compareBooleans = compareBooleans; - function compareMessageText(text1, text2) { + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; while (text1 && text2) { // We still have both chains. var string1 = isString(text1) ? text1 : text1.messageText; @@ -3446,6 +3387,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -3464,7 +3413,7 @@ var ts; } ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { - return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { @@ -3989,7 +3938,7 @@ var ts; /** * Matches any single directory segment unless it is the last segment and a .min.js file * Breakdown: - * [^./] # matches everything up to the first . character (excluding directory seperators) + * [^./] # matches everything up to the first . character (excluding directory separators) * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension */ singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", @@ -4051,7 +4000,7 @@ var ts; var subpattern = ""; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); - var lastComponent = lastOrUndefined(components); + var lastComponent = last(components); if (usage !== "exclude" && lastComponent === "**") { return undefined; } @@ -4277,11 +4226,11 @@ var ts; return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { @@ -4487,7 +4436,8 @@ var ts; } Debug.fail = fail; function assertDefined(value, message) { - assert(value !== undefined && value !== null, message); + if (value === undefined || value === null) + return fail(message); return value; } Debug.assertDefined = assertDefined; @@ -4671,10 +4621,7 @@ var ts; */ function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); - if (ext !== undefined) { - return ext; - } - Debug.fail("File " + path + " has unknown extension."); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; function isAnySupportedFileExtension(path) { @@ -5118,6 +5065,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: this is used as if it's certainly defined in many places. ts.sys = (function () { // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual // byte order mark from the specified encoding. Using any other byte order mark does @@ -5299,6 +5247,7 @@ var ts; return watchDirectoryRecursively(directoryName, callback); } watchDirectory(directoryName, callback); + return undefined; // TODO: GH#18217 }; } function createNonPollingWatchFile() { @@ -5330,7 +5279,7 @@ var ts; var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" var fileName = !ts.isString(relativeFileName) - ? undefined + ? undefined // TODO: GH#18217 : ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); @@ -5579,6 +5528,7 @@ var ts; switch (entryKind) { case 0 /* File */: return stat.isFile(); case 1 /* Directory */: return stat.isDirectory(); + default: return false; } } catch (e) { @@ -6274,7 +6224,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -6602,6 +6552,8 @@ var ts; _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Enable_strict_checking_of_any_type: diag(6200, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_any_type_6200", "Enable strict checking of 'any' type."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -6629,7 +6581,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -6710,6 +6662,7 @@ var ts; Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -6779,6 +6732,7 @@ var ts; Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), }; })(ts || (ts = {})); var ts; @@ -7485,8 +7439,9 @@ var ts; } ts.isIdentifierText = isIdentifierText; // Creates a scanner over a (possibly unspecified) range of a piece of text. - function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; // Current position (end position of text of current token) var pos; // end of text @@ -7942,7 +7897,7 @@ var ts; var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); - // Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator if (ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (separatorAllowed) { @@ -8758,7 +8713,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function packageIdToString(_a) { var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; @@ -8896,6 +8851,27 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Appends a range of value to begin of an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + */ + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; /** * Determine if the given comment is a triple-slash * @@ -8985,7 +8961,7 @@ var ts; */ function getEmitFlags(node) { var emitNode = node.emitNode; - return emitNode && emitNode.flags; + return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { @@ -9019,7 +8995,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return node.text; } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { @@ -9127,7 +9103,7 @@ var ts; case 212 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block - return parentNode && !ts.isFunctionLike(parentNode); + return !ts.isFunctionLike(parentNode); } return false; } @@ -9219,7 +9195,7 @@ var ts; case 8 /* NumericLiteral */: return escapeLeadingUnderscores(name.text); case 146 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; + return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: ts.Debug.assertNever(name); } @@ -9233,6 +9209,8 @@ var ts; return entityNameToString(name.left) + "." + entityNameToString(name.right); case 184 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); } } ts.entityNameToString = entityNameToString; @@ -9441,7 +9419,7 @@ var ts; // falls through case 145 /* QualifiedName */: case 184 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: + case 99 /* ThisKeyword */: { var parent = node.parent; if (parent.kind === 164 /* TypeQuery */) { return false; @@ -9490,6 +9468,7 @@ var ts; // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } + } } return false; } @@ -9685,15 +9664,16 @@ var ts; return ts.filter(objectLiteral.properties, function (property) { if (property.kind === 269 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); - return key === propName || (key2 && key2 === propName); + return key === propName || (!!key2 && key2 === propName); } + return false; }); } ts.getPropertyAssignment = getPropertyAssignment; function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { var expression = tsConfigSourceFile.statements[0].expression; - return ts.isObjectLiteralExpression(expression) && expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); } } ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; @@ -9716,10 +9696,11 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 273 /* SourceFile */); while (true) { node = node.parent; if (!node) { - return undefined; + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { case 146 /* ComputedPropertyName */: @@ -9924,20 +9905,22 @@ var ts; ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node, parent, grandparent); + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; function nodeOrChildIsDecorated(node, parent, grandparent) { - return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { case 234 /* ClassDeclaration */: - return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 case 153 /* MethodDeclaration */: case 156 /* SetAccessor */: - return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; } } ts.childIsDecorated = childIsDecorated; @@ -10081,15 +10064,15 @@ var ts; } ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536 /* JavaScriptFile */); + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; function isInJsonFile(node) { - return node && !!(node.flags & 16777216 /* JsonFile */); + return !!node && !!(node.flags & 16777216 /* JsonFile */); } ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { - return node && !!(node.flags & 2097152 /* JSDoc */); + return !!node && !!(node.flags & 2097152 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; function isJSDocIndexSignature(node) { @@ -10360,7 +10343,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 243 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 243 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { @@ -10397,16 +10380,18 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ && - node.expression.right; + node.expression.operatorToken.kind === 58 /* EqualsToken */ + ? node.expression.right + : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ && - node.expression.right.right; + node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + ? node.expression.right.right + : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { @@ -10420,15 +10405,14 @@ var ts; } } function getSingleVariableOfVariableStatement(node) { - return ts.isVariableStatement(node) && - node.declarationList.declarations.length > 0 && - node.declarationList.declarations[0]; + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } function getNestedModuleDeclaration(node) { - return node.kind === 238 /* ModuleDeclaration */ && + return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 238 /* ModuleDeclaration */ && - node.body; + node.body.kind === 238 /* ModuleDeclaration */ + ? node.body + : undefined; } function getJSDocCommentsAndTags(hostNode) { var result; @@ -10517,12 +10501,12 @@ var ts; ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { var last = ts.lastOrUndefined(s.parameters); - return last && isRestParameter(last); + return !!last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || type && type.kind === 284 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 284 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -10660,9 +10644,10 @@ var ts; switch (name.kind) { case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - if (ts.isDeclaration(name.parent)) { - return name.parent.name === name; + case 8 /* NumericLiteral */: { + var parent = name.parent; + if (ts.isDeclaration(parent)) { + return parent.name === name; } else if (ts.isQualifiedName(name.parent)) { var tag = name.parent.parent; @@ -10672,6 +10657,7 @@ var ts; var binExp = name.parent.parent; return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; } + } default: return false; } @@ -10876,7 +10862,7 @@ var ts; */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); - return name && isDynamicName(name); + return !!name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -11169,7 +11155,7 @@ var ts; } ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; function createDiagnosticCollection() { - var nonFileDiagnostics = []; + var nonFileDiagnostics = []; // See GH#19873 var filesWithDiagnostics = []; var fileDiagnostics = ts.createMap(); var hasReadNonFileDiagnostics = false; @@ -11187,7 +11173,7 @@ var ts; if (diagnostic.file) { diagnostics = fileDiagnostics.get(diagnostic.file.fileName); if (!diagnostics) { - diagnostics = []; + diagnostics = []; // See GH#19873 fileDiagnostics.set(diagnostic.file.fileName, diagnostics); ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); } @@ -11334,7 +11320,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); + linePos = output.length - s.length + ts.last(lineStartsOfS); } } } @@ -11509,7 +11495,7 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { @@ -11517,6 +11503,7 @@ var ts; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 var firstAccessor; var secondAccessor; var getAccessor; @@ -11713,13 +11700,13 @@ var ts; // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; } } } @@ -11888,7 +11875,7 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 206 /* ExpressionWithTypeArguments */ && + if (ts.isExpressionWithTypeArguments(node) && node.parent.token === 85 /* ExtendsKeyword */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -12858,7 +12845,7 @@ var ts; // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) ts.localizedDiagnosticMessages = JSON.parse(fileContents); } - catch (e) { + catch (_a) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); } @@ -12987,6 +12974,7 @@ var ts; return !!node.name; // A 'name' property should always be a DeclarationName. } ts.isNamedDeclaration = isNamedDeclaration; + // TODO: GH#18217 This is often used as if it returns a defined result function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -13912,7 +13900,6 @@ var ts; // Identifiers /* @internal */ function isGeneratedIdentifier(node) { - // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; @@ -14610,8 +14597,10 @@ var ts; ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times function hasJSDocNodes(node) { - return !!node.jsDoc && node.jsDoc.length > 0; + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; /** True if has type node attached to it. */ @@ -15278,6 +15267,7 @@ var ts; // becoming detached from any SourceFile). It is recommended that this SourceFile not // be used once 'update' is called on it. function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. // We will manually port the flag to the new source file. @@ -15403,6 +15393,7 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); @@ -15604,6 +15595,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -16124,7 +16116,7 @@ var ts; case 14 /* JsxChildren */: return true; } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); @@ -16213,6 +16205,8 @@ var ts; return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; case 14 /* JsxChildren */: return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; } } function isVariableDeclaratorListTerminator() { @@ -16544,6 +16538,7 @@ var ts; case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; + default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` } } // Parses a comma-delimited list of elements @@ -16676,7 +16671,7 @@ var ts; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } @@ -16915,7 +16910,7 @@ var ts; if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); + signature.parameters = parseParameterList(flags); // TODO: GH#18217 if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { signature.type = parseTypeOrTypePredicate(); return signature.type !== undefined; @@ -17077,7 +17072,7 @@ var ts; if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return true; } - var idToken; + var idToken = false; // Eat up all modifiers, but hold on to the last one in case it is actually an identifier while (ts.isModifierKind(token())) { idToken = true; @@ -17200,7 +17195,7 @@ var ts; parseExpected(19 /* OpenParenToken */); node.type = parseType(); if (!node.type) { - return undefined; + return undefined; // TODO: GH#18217 } parseExpected(20 /* CloseParenToken */); return finishNode(node); @@ -17532,7 +17527,7 @@ var ts; } function parseTypeWorker(noConditionalTypes) { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162 /* FunctionType */); + return parseFunctionOrConstructorType(162 /* FunctionType */); // TODO: GH#18217 } if (token() === 94 /* NewKeyword */) { return parseFunctionOrConstructorType(163 /* ConstructorType */); @@ -18499,7 +18494,7 @@ var ts; badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -19554,6 +19549,7 @@ var ts; missing.modifiers = node.modifiers; return finishNode(missing); } + return undefined; // TODO: GH#18217 } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { @@ -19897,7 +19893,7 @@ var ts; return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. - ts.Debug.fail("Should not have attempted to parse class member declaration."); + return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 204 /* ClassExpression */); @@ -19945,14 +19941,12 @@ var ts; } function parseHeritageClause() { var tok = token(); - if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { - var node = createNode(267 /* HeritageClause */); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; + ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(267 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); } function parseExpressionWithTypeArguments() { var node = createNode(206 /* ExpressionWithTypeArguments */); @@ -20384,8 +20378,8 @@ var ts; PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } var content = sourceText; - start = start || 0; var end = length === undefined ? content.length : start + length; length = end - start; ts.Debug.assert(start >= 0); @@ -20715,7 +20709,7 @@ var ts; var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -20795,7 +20789,7 @@ var ts; while (parseOptional(23 /* DotToken */)) { var prop = createNode(184 /* PropertyAccessExpression */, node.pos); prop.expression = node; - prop.name = parseJSDocIdentifierName(); + prop.name = parseJSDocIdentifierName(); // TODO: GH#18217 node = finishNode(prop); } return node; @@ -20935,7 +20929,7 @@ var ts; var child = tryParseChildTag(target); if (child && child.kind === 292 /* JSDocParameterTag */ && target !== 4 /* CallbackParameter */ && - (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { // TODO: GH#18217 return false; } return child; @@ -21581,7 +21575,7 @@ var ts; context.pragmas = ts.createMap(); for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { var pragma = pragmas_1[_i]; - if (context.pragmas.has(pragma.name)) { + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 var currentValue = context.pragmas.get(pragma.name); if (currentValue instanceof Array) { currentValue.push(pragma.args); @@ -21610,6 +21604,7 @@ var ts; var referencedFiles_1 = context.referencedFiles; var typeReferenceDirectives_1 = context.typeReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } @@ -21626,10 +21621,7 @@ var ts; break; } case "amd-dependency": { - context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { - var _b = _a.arguments, name = _b.name, path = _b.path; - return ({ name: name, path: path }); - }); + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 break; } case "amd-module": { @@ -21652,7 +21644,7 @@ var ts; case "ts-check": { // _last_ of either nocheck or check in a file is the "winner" ts.forEach(ts.toArray(entryOrList), function (entry) { - if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 context.checkJsDirective = { enabled: key === "ts-check", end: entry.range.end, @@ -22036,7 +22028,7 @@ var ts; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); // TODO: GH#18217 } /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @@ -22836,6 +22828,7 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -22877,7 +22870,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 217 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -23261,7 +23254,7 @@ var ts; // We do that by making an anonymous type literal symbol, and then setting the function // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. - var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 addDeclarationToSymbol(symbol, node, 131072 /* Signature */); var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); @@ -23507,6 +23500,16 @@ var ts; var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } + function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } function bind(node) { if (!node) { return; @@ -24036,7 +24039,7 @@ var ts; (symbol.exports || (symbol.exports = ts.createSymbolTable())); // Declare the method/property var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); // TODO: GH#18217 var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); @@ -24066,7 +24069,8 @@ var ts; } else { var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); - ts.Debug.assert(!!s && !!s.exports); + if (!s || !s.exports) + return ts.Debug.fail(); return action(e.name, s.exports.get(e.name.escapedText)); } } @@ -24207,7 +24211,7 @@ var ts; } function bindTypeParameter(node) { if (ts.isJSDocTemplateTag(node.parent)) { - var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 if (container_1) { if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); @@ -24227,7 +24231,7 @@ var ts; declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } else { - bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { @@ -24237,7 +24241,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -24255,22 +24259,22 @@ var ts; (node.kind === 237 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 4194304 /* Ambient */) && - (node.kind !== 213 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); } } } @@ -24286,8 +24290,8 @@ var ts; ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { return isExportsOrModuleExportsOrAlias(sourceFile, node) || @@ -25282,11 +25286,11 @@ var ts; } function visitSymbol(symbol) { if (!symbol) { - return; + return false; } var symbolId = ts.getSymbolId(symbol); if (visitedSymbols[symbolId]) { - return; + return false; } visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { @@ -25308,6 +25312,7 @@ var ts; visitSymbol(entity); } }); + return false; } } } @@ -25321,7 +25326,7 @@ var ts; ts.trace = trace; /* @internal */ function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; + return !!compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; function withPackageId(packageId, r) { @@ -25501,7 +25506,6 @@ var ts; } } function secondaryLookup() { - var resolvedFile; var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations @@ -25509,7 +25513,7 @@ var ts; trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); + var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -25582,7 +25586,7 @@ var ts; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; + return undefined; // TODO: GH#18217 } var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { @@ -25694,7 +25698,7 @@ var ts; result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; default: - ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -25947,7 +25951,7 @@ var ts; var originalPath = void 0; if (!compilerOptions.preserveSymlinks && resolvedValue) { originalPath = resolvedValue.path; - var path = realPath(resolved_1.value.path, host, traceEnabled); + var path = realPath(resolvedValue.path, host, traceEnabled); if (path === originalPath) { originalPath = undefined; } @@ -26066,7 +26070,7 @@ var ts; function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); @@ -26105,7 +26109,7 @@ var ts; } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, ext: ext }; + return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ @@ -26495,6 +26499,7 @@ var ts; var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var strictAny = ts.getStrictOptionValue(compilerOptions, "strictAny"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; @@ -26527,9 +26532,10 @@ var ts; location = ts.getParseTreeNode(location); return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); }, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, @@ -26541,8 +26547,8 @@ var ts; getBaseTypes: getBaseTypes, getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node ? getTypeFromTypeNode(node) : unknownType; }, getParameterType: getTypeAtPosition, @@ -26569,8 +26575,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getShorthandAssignmentValueSymbol(node) : undefined; }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, getExportSymbolOfSymbol: function (symbol) { @@ -26580,8 +26586,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getTypeOfNode(node) : unknownType; }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; }, signatureToString: function (signature, enclosingDeclaration, flags, kind) { @@ -26611,41 +26617,41 @@ var ts; getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, - getContextualTypeForArgumentAtIndex: function (node, argIndex) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); }, - getContextualTypeForJsxAttribute: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxAttributeLike); + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); apparentArgumentCount = theArgumentCount; var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; apparentArgumentCount = undefined; return res; }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); }, - isValidPropertyAccessForCompletions: function (node, type, property) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); return !!node && isValidPropertyAccessForCompletions(node, type, property); }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); return declaration ? getSignatureFromDeclaration(declaration) : undefined; }, isImplementationOfOverload: function (node) { @@ -26657,7 +26663,8 @@ var ts; var links = getSymbolLinks(symbol); if (!links.immediateTarget) { var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); } return links.immediateTarget; @@ -26668,13 +26675,13 @@ var ts; getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); return node ? isOptionalParameter(node) : false; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, @@ -26720,8 +26727,8 @@ var ts; node = ts.getParseTreeNode(node); return node && tryGetThisTypeAt(node); }, - getTypeArgumentConstraint: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file) { @@ -27028,6 +27035,7 @@ var ts; typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); }, buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); }, buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { @@ -27041,12 +27049,12 @@ var ts; buildParameterDisplay: function (symbol, writer, enclosing, flags) { var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 }, buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 }, buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); @@ -27059,13 +27067,13 @@ var ts; buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { var printer = ts.createPrinter({ removeComments: true }); var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); - var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; - var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; // TODO: GH#18217 + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); // TODO: GH#18217 printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); }, buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { var printer = ts.createPrinter({ removeComments: true }); - var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); // TODO: GH#18217 printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); }, buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { @@ -27077,7 +27085,7 @@ var ts; } var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 } }; function emitTextWriterWrapper(underlying) { @@ -27164,7 +27172,7 @@ var ts; } var jsxPragma = file_1.pragmas.get("jsx"); if (jsxPragma) { - var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file_1.localJsxFactory) { return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText; @@ -27459,7 +27467,7 @@ var ts; if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); @@ -27534,7 +27542,8 @@ var ts; break; } // ForIn/ForOf case - use site should not be used in expression part - return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); } function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { return !!ts.findAncestor(usage, function (current) { @@ -27560,6 +27569,7 @@ var ts; } } } + return false; }); } } @@ -27838,7 +27848,7 @@ var ts; if (!result) { if (nameNotFoundMessage) { if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && @@ -27890,7 +27900,7 @@ var ts; if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 241 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } } @@ -27918,7 +27928,7 @@ var ts; if (decl.kind === 147 /* TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 } } } @@ -27945,7 +27955,7 @@ var ts; // No static member is present. // Check if we're in an instance method and look for a relevant instance member. if (location === container && !ts.hasModifier(location, 32 /* Static */)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); return true; @@ -27958,11 +27968,11 @@ var ts; } function checkAndReportErrorForExtendingInterface(errorLocation) { var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); - if (isError) { + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; + return false; } /** * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, @@ -28038,7 +28048,8 @@ var ts; ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 237 /* EnumDeclaration */) ? d : undefined; }); - ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); @@ -28056,7 +28067,7 @@ var ts; * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. */ function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { switch (node.kind) { @@ -28191,12 +28202,13 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 } } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { var name = specifier.propertyName || specifier.name; @@ -28261,6 +28273,7 @@ var ts; return getNodeLinks(expression).resolvedSymbol; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { case 242 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); @@ -28277,6 +28290,8 @@ var ts; return getTargetOfExportAssignment(node, dontRecursivelyResolve); case 241 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); } } /** @@ -28287,11 +28302,10 @@ var ts; if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || (symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); } function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); - return shouldResolve ? resolveAlias(symbol) : symbol; + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); @@ -28299,7 +28313,8 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -28332,7 +28347,8 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); if (node.kind === 248 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); @@ -28431,7 +28447,7 @@ var ts; } } else { - ts.Debug.assertNever(name, "Unknown entity name kind."); + throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -28492,7 +28508,7 @@ var ts; return ambientModule; } var currentSourceFile = ts.getSourceFileOfNode(location); - var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -28566,8 +28582,6 @@ var ts; /*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)); errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } - // 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) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } @@ -28899,7 +28913,7 @@ var ts; // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -28927,6 +28941,11 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } @@ -28934,7 +28953,7 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; @@ -29008,7 +29027,7 @@ var ts; return hasAccessibleDeclarations; } else { - if (ts.some(symbol.declarations, hasExternalModuleSymbol)) { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // Any meaning of a module symbol is always accessible via an `import` type return { accessibility: 0 /* Accessible */ @@ -29059,6 +29078,9 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 273 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { @@ -29144,7 +29166,7 @@ var ts; var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { - var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); @@ -29152,6 +29174,7 @@ var ts; } } function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); function signatureToStringWorker(writer) { var sigOutput; @@ -29164,15 +29187,16 @@ var ts; var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 return writer; } } function typeToString(type, enclosingDeclaration, flags, writer) { - if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; } + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } 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"); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); @@ -29185,6 +29209,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } return flags & 9469291 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { @@ -29201,7 +29226,7 @@ var ts; var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; - return result; + return result; // TODO: GH#18217 }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); @@ -29249,7 +29274,7 @@ var ts; function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, - flags: flags, + flags: flags || 0 /* None */, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, @@ -29264,7 +29289,7 @@ var ts; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { return ts.createKeywordTypeNode(119 /* AnyKeyword */); @@ -29354,9 +29379,10 @@ var ts; !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); @@ -29375,7 +29401,7 @@ var ts; if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } - return undefined; + return undefined; // TODO: GH#18217 } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { @@ -29406,7 +29432,7 @@ var ts; if (type.flags & 4194304 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } - ts.Debug.fail("Should be unreachable."); + return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -29480,7 +29506,7 @@ var ts; if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively - (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } } @@ -29532,7 +29558,7 @@ var ts; return ts.createTupleTypeNode([]); } context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && @@ -29655,7 +29681,7 @@ var ts; var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(propertySymbol.declarations); + var decl = ts.first(propertySymbol.declarations); var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); if (name && context.tracker.trackSymbol) { context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); @@ -29718,7 +29744,7 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } @@ -29795,7 +29821,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration @@ -29823,12 +29849,12 @@ var ts; } } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { - context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { - chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } else { @@ -29858,7 +29884,7 @@ var ts; // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) && + (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; @@ -30035,6 +30061,7 @@ var ts; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); @@ -30115,7 +30142,7 @@ var ts; return "default"; } if (symbol.declarations && symbol.declarations.length) { - if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { + if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { // TODO: GH#18217 var file_3 = ts.getDeclarationOfKind(symbol, 273 /* SourceFile */); if (!file_3 || !context.tracker.moduleResolverHost) { if (context.tracker.trackReferencedAmbientModule) { @@ -30123,7 +30150,7 @@ var ts; if (ts.length(ambientDecls)) { for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { var decl = ambientDecls_1[_i]; - context.tracker.trackReferencedAmbientModule(decl); + context.tracker.trackReferencedAmbientModule(decl); // TODO: GH#18217 } } } @@ -30329,22 +30356,22 @@ var ts; } function hasType(target, propertyName) { if (propertyName === 0 /* Type */) { - return getSymbolLinks(target).type; + return !!getSymbolLinks(target).type; } if (propertyName === 2 /* DeclaredType */) { - return getSymbolLinks(target).declaredType; + return !!getSymbolLinks(target).declaredType; } if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return target.resolvedBaseConstructorType; + return !!target.resolvedBaseConstructorType; } if (propertyName === 3 /* ResolvedReturnType */) { - return target.resolvedReturnType; + return !!target.resolvedReturnType; } if (propertyName === 4 /* ResolvedBaseConstraint */) { var bc = target.resolvedBaseConstraint; - return bc && bc !== circularConstraintType; + return !!bc && bc !== circularConstraintType; } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -30354,7 +30381,7 @@ var ts; return resolutionResults.pop(); } function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { case 231 /* VariableDeclaration */: case 232 /* VariableDeclarationList */: @@ -30366,8 +30393,7 @@ var ts; default: return true; } - }); - return node && node.parent; + }).parent; } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 @@ -30480,7 +30506,7 @@ var ts; } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - var nameType = isLate && checkComputedPropertyName(name); + var nameType = isLate ? checkComputedPropertyName(name) : undefined; var text = isLate ? getLateBoundNameFromType(nameType) : isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : ts.getTextOfPropertyName(name); @@ -30742,7 +30768,7 @@ var ts; definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 /* Nullable */ | 16777216 /* ContainsWideningType */)); }) ? constructorTypes : types; + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(12288 /* Nullable */ | 16777216 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); @@ -30818,7 +30844,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + if (!lastElement || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. @@ -30838,6 +30864,8 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } return pattern.kind === 179 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); @@ -30956,7 +30984,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } else { - ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); } if (!popTypeResolution()) { type = reportCircularityError(symbol); @@ -31158,16 +31186,18 @@ var ts; function getTargetType(type) { return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. function hasBaseType(type, checkBase) { return check(type); function check(type) { if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); + return target === checkBase || ts.some(getBaseTypes(target), check); } else if (type.flags & 262144 /* Intersection */) { - return ts.forEach(type.types, check); + return ts.some(type.types, check); } + return false; } } // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. @@ -31183,7 +31213,7 @@ var ts; // Return the outer type parameters of a node or undefined if the node has no outer type parameters. function getOuterTypeParameters(node, includeThisTypes) { while (true) { - node = node.parent; + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead if (!node) { return undefined; } @@ -31264,7 +31294,7 @@ var ts; } if (type.flags & 1081344 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } @@ -31396,7 +31426,7 @@ var ts; // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a // partial instantiation of the members without the base types fully resolved - type.members = undefined; + type.members = undefined; // TODO: GH#18217 } return type.resolvedBaseTypes = [baseType]; } @@ -31414,8 +31444,8 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return type.flags & (65536 /* Object */ | 134217728 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || - type.flags & 262144 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return !!(type.flags & (65536 /* Object */ | 134217728 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 262144 /* Intersection */) && !ts.some(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -31605,7 +31635,7 @@ var ts; if (declaration.kind === 237 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; memberTypeList.push(memberType); } @@ -31720,7 +31750,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) && + return (node.kind === 154 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -31805,7 +31835,7 @@ var ts; */ function hasLateBindableName(node) { var name = ts.getNameOfDeclaration(node); - return name && isLateBindableName(name); + return !!name && isLateBindableName(name); } /** * Indicates whether a declaration has a dynamic name that cannot be late-bound. @@ -31829,6 +31859,7 @@ var ts; if (type.flags & 96 /* StringOrNumberLiteral */) { return ts.escapeLeadingUnderscores("" + type.value); } + return ts.Debug.fail(); } /** * Adds a declaration to a late-bound dynamic member. This performs the same function for @@ -31846,8 +31877,7 @@ var ts; symbol.declarations.push(member); } if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } } @@ -32075,7 +32105,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); @@ -32147,6 +32177,7 @@ var ts; if (unionSignatures.length > 1) { var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); thisParameter = createSymbolWithType(signature.thisParameter, thisType); } @@ -32412,7 +32443,7 @@ var ts; return type.declaration.typeParameter.constraint; } function isMappedTypeWithKeyofConstraintDeclaration(type) { - var constraintDeclaration = getConstraintDeclarationForMappedType(type); + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 return constraintDeclaration.kind === 174 /* TypeOperator */ && constraintDeclaration.operator === 128 /* KeyOfKeyword */; } @@ -32454,7 +32485,7 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); } function isGenericMappedType(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -33061,14 +33092,6 @@ var ts; } return minTypeArgumentCount; } - /** - * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined - * when a default type is supplied, a new array will be created and returned. - * - * @param typeArguments The supplied type arguments. - * @param typeParameters The requested type parameters. - * @param minTypeArgumentCount The minimum number of required type arguments. - */ function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { @@ -33103,7 +33126,7 @@ var ts; var hasLiteralTypes = false; var minArgumentCount = 0; var thisParameter = void 0; - var hasThisParameter = void 0; + var hasThisParameter = false; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && @@ -33190,7 +33213,7 @@ var ts; } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 } else if (classType) { return classType; @@ -33233,7 +33256,7 @@ var ts; return node.name.kind === 146 /* ComputedPropertyName */ && traverse(node.name); default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); } } } @@ -33243,7 +33266,7 @@ var ts; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { var decl = symbol.declarations[i]; - var node = ts.isPropertyAccessExpression(decl) ? ts.getAssignedJavascriptInitializer(decl) : decl; + var node = ts.isPropertyAccessExpression(decl) ? ts.getAssignedJavascriptInitializer(decl) : decl; // TODO: GH#18217 if (!ts.isFunctionLike(node)) continue; // Don't include signature if node is the implementation of an overloaded function. A node is considered @@ -33333,9 +33356,10 @@ var ts; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + var type = getTypeOfSymbol(ts.last(signature.parameters)); if (ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { - return type.typeArguments[0]; + var t = type.typeArguments[0]; + return strictAny && t.flags & 1 /* Any */ ? unknownType : t; } } return anyType; @@ -33394,7 +33418,7 @@ var ts; // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 154 /* Constructor */ || signature.declaration.kind === 158 /* ConstructSignature */; + var isConstructor = signature.declaration.kind === 154 /* Constructor */ || signature.declaration.kind === 158 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -33676,7 +33700,8 @@ var ts; var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); if (referenceType || assignedType) { - return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -33727,7 +33752,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return node.flags & 2097152 /* JSDoc */ && node.kind === 161 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 161 /* TypeReference */; } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -33774,7 +33799,7 @@ var ts; var indexed = getTypeFromTypeNode(typeArgs[0]); var target = getTypeFromTypeNode(typeArgs[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); } return anyType; } @@ -33911,7 +33936,7 @@ var ts; return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { - return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. @@ -34315,16 +34340,19 @@ var ts; // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); if (includes & 16384 /* Never */) { return neverType; } - if (includes & 1 /* Any */) { - return includes & 33554432 /* Wildcard */ ? wildcardType : anyType; + if (includes & 33554432 /* Wildcard */) { + return wildcardType; + } + if (!strictAny && includes & 1 /* Any */) { + return anyType; + } + if (!strictNullChecks && includes & 12288 /* Nullable */) { + return includes & 4096 /* Undefined */ ? undefinedType : nullType; } if (includes & 2 /* String */ && includes & 32 /* StringLiteral */ || includes & 4 /* Number */ && includes & 64 /* NumberLiteral */ || @@ -34334,6 +34362,9 @@ var ts; if (includes & 67108864 /* EmptyObject */ && !(includes & 65536 /* Object */)) { typeSet.push(emptyObjectType); } + if (typeSet.length === 0) { + return anyType; + } if (typeSet.length === 1) { return typeSet[0]; } @@ -34441,7 +34472,7 @@ var ts; break; } } - return links.resolvedType; + return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { var type = createType(1048576 /* IndexedAccess */); @@ -34530,12 +34561,12 @@ var ts; var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - t.stringIndexInfo && !t.numberIndexInfo; + !!t.stringIndexInfo && !t.numberIndexInfo; } return false; } function isMappedTypeToNever(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; } function getSimplifiedType(type) { return type.flags & 1048576 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; @@ -34720,7 +34751,7 @@ var ts; result.mapper = mapper; result.combinedMapper = combinedMapper; result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } function getTrueTypeFromConditionalType(type) { @@ -34849,7 +34880,7 @@ var ts; } } } - return links.resolvedType; + return links.resolvedType; // TODO: GH#18217 } function resolveImportSymbolType(node, links, symbol, meaning) { links.resolvedSymbol = symbol; @@ -35004,7 +35035,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -35138,7 +35171,7 @@ var ts; case 71 /* Identifier */: case 145 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 default: return unknownType; } @@ -35361,21 +35394,21 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_3; })) { - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { case 173 /* ThisType */: - return tp.isThisType; + return !!tp.isThisType; case 71 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNode(node) === tp; case 164 /* TypeQuery */: return true; } - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -35510,9 +35543,9 @@ var ts; case 153 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); case 183 /* ObjectLiteralExpression */: - return ts.forEach(node.properties, isContextSensitive); + return ts.some(node.properties, isContextSensitive); case 182 /* ArrayLiteralExpression */: - return ts.forEach(node.elements, isContextSensitive); + return ts.some(node.elements, isContextSensitive); case 200 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); @@ -35524,13 +35557,17 @@ var ts; case 190 /* ParenthesizedExpression */: return isContextSensitive(node.expression); case 262 /* JsxAttributes */: - return ts.forEach(node.properties, isContextSensitive); - case 261 /* JsxAttribute */: + return ts.some(node.properties, isContextSensitive); + case 261 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. - return node.initializer && isContextSensitive(node.initializer); - case 264 /* JsxExpression */: + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 264 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) - return node.expression && isContextSensitive(node.expression); + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } } return false; } @@ -35540,7 +35577,7 @@ var ts; return false; } // Functions with any parameters that lack type annotations are context sensitive. - if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } if (node.kind !== 192 /* ArrowFunction */) { @@ -35552,7 +35589,8 @@ var ts; } } // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return node.body.kind === 212 /* Block */ ? false : isContextSensitive(node.body); + var body = node.body; + return body.kind === 212 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -35692,6 +35730,7 @@ var ts; var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { @@ -35713,7 +35752,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -35805,8 +35844,8 @@ var ts; function isEmptyObjectType(type) { return type.flags & 65536 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 134217728 /* NonPrimitive */ ? true : - type.flags & 131072 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 262144 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + type.flags & 131072 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 262144 /* Intersection */ ? !ts.some(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -35881,7 +35920,7 @@ var ts; if (s & 1024 /* UniqueESSymbol */ || t & 1024 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { - if (s & 1 /* Any */) + if (s & 1 /* Any */ && (!strictAny || source === unknownType || t & 65536 /* Object */ && isEmptyObjectType(target))) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because @@ -35949,7 +35988,7 @@ var ts; errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); // TODO: GH#18217 } // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement if (headMessage && errorNode && !result && source.symbol) { @@ -36023,6 +36062,7 @@ var ts; * * Ternary.False if they are not related. */ function isRelatedTo(source, target, reportErrors, headMessage) { + if (reportErrors === void 0) { reportErrors = false; } if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 8388608 /* FreshLiteral */) { source = source.regularType; } @@ -36216,7 +36256,8 @@ var ts; // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. - ts.Debug.assert(!!errorNode); + if (!errorNode) + return { value: ts.Debug.fail() }; if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. @@ -36230,8 +36271,9 @@ var ts; var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; - if (ts.isIdentifier(propDeclaration.name)) { - suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); } } if (suggestion !== undefined) { @@ -36896,7 +36938,7 @@ var ts; // in the context of the target signature before checking the relationship. Ideally we'd do // this regardless of the number of signatures, but the potential costs are prohibitive due // to the quadratic nature of the logic below. - var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); } else { @@ -36992,7 +37034,7 @@ var ts; if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } // if T is related to U. - return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 } if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; @@ -37112,7 +37154,7 @@ var ts; return type.flags & 32768 /* TypeParameter */ && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -37366,7 +37408,7 @@ var ts; return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); } function isArrayType(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, @@ -37811,12 +37853,12 @@ var ts; } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); } return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 393216 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { @@ -38255,7 +38297,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); + return !!constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -38280,10 +38322,12 @@ var ts; // all inferences were made to top-level occurrences 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) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. @@ -38399,7 +38443,8 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 179 /* ObjectBindingPattern */) { + var parent = element.parent; + if (parent.kind === 179 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { case 71 /* Identifier */: @@ -38415,7 +38460,7 @@ var ts; } } else { - return "" + element.parent.elements.indexOf(element); + return "" + parent.elements.indexOf(element); } } function isMatchingReference(source, target) { @@ -38443,7 +38488,7 @@ var ts; } if (source.parent.parent.kind === 231 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; - return maybeId && isMatchingReference(maybeId, t.expression); + return !!maybeId && isMatchingReference(maybeId, t.expression); } } return false; @@ -38481,7 +38526,7 @@ var ts; var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -38807,9 +38852,6 @@ var ts; } return f(type) ? type : neverType; } - // Apply a mapping function to a type and return the resulting type. If the source type - // 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; @@ -39729,7 +39771,7 @@ var ts; // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container !== undefined) { + while (container.kind !== 273 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 151 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; @@ -40345,7 +40387,7 @@ var ts; if (funcHasRestParameters && indexOfParameter === (func.parameters.length - 1) && isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + return getTypeOfSymbol(ts.last(contextualSignature.parameters)); } } } @@ -40447,7 +40489,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); + var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -40501,7 +40543,7 @@ var ts; case 6 /* Prototype */: return false; default: - ts.Debug.assertNever(kind); + return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { @@ -40590,6 +40632,25 @@ var ts; return getContextualType(attribute.parent); } } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 71 /* Identifier */: + return true; + case 184 /* PropertyAccessExpression */: + case 190 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { @@ -40606,8 +40667,8 @@ var ts; continue; if (prop.kind !== 269 /* PropertyAssignment */) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); @@ -40703,8 +40764,8 @@ var ts; return undefined; } function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -41287,7 +41348,7 @@ var ts; case 71 /* Identifier */: return ts.isIntrinsicJsxName(tagName.escapedText); default: - ts.Debug.fail(); + return ts.Debug.fail(); } } function checkJsxAttribute(node, checkMode) { @@ -41501,6 +41562,7 @@ var ts; return instantiatedSignatures; } function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (reportErrors === void 0) { reportErrors = false; } if (!node.typeArguments) { return; } @@ -41523,7 +41585,7 @@ var ts; } } // JSX global fallback - return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -41639,6 +41701,7 @@ var ts; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); + // TODO: GH#18217: callReturnType should always be defined... var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { @@ -41647,7 +41710,7 @@ var ts; var attribute = _b[_a]; if (ts.isJsxAttribute(attribute) && isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { + !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 shouldBeCandidate = false; break; } @@ -41762,7 +41825,7 @@ var ts; if (!ts.length(instantiatedSignatures)) { return unknownType; } - var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -41776,7 +41839,7 @@ var ts; checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } var isJs = ts.isInJavaScriptFile(openingLikeElement); - return getUnionType(ts.map(instantiatedSignatures, function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); + return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -42090,7 +42153,7 @@ var ts; if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } } @@ -42130,7 +42193,7 @@ var ts; } if (type.flags & 32768 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type - type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); @@ -42231,7 +42294,7 @@ var ts; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { - error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; } @@ -42489,7 +42552,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, left, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 131072 /* Union */) && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 131072 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -42646,7 +42709,7 @@ var ts; var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { - index++; + index = index + 1; } else { lastParent = parent; @@ -42689,7 +42752,7 @@ var ts; if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call var typeArguments; // Type arguments (undefined if none) - var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". @@ -42703,8 +42766,7 @@ var ts; if (node.template.kind === 201 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. - var lastSpan = ts.lastOrUndefined(node.template.templateSpans); - ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { @@ -42882,7 +42944,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -42939,7 +43001,7 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { return false; } } @@ -42991,7 +43053,7 @@ var ts; function getEffectiveCallArguments(node) { if (node.kind === 188 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; + var args_4 = [undefined]; // TODO: GH#18217 if (template.kind === 201 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -43052,6 +43114,8 @@ var ts; // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; + default: + return ts.Debug.fail(); } } else { @@ -43139,14 +43203,15 @@ var ts; // otherwise, if the member name is a computed property name it will // be either string or symbol. var element = node; - switch (element.name.kind) { + var name = element.name; + switch (name.kind) { case 71 /* Identifier */: - return getLiteralType(ts.idText(element.name)); + return getLiteralType(ts.idText(name)); case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralType(element.name.text); + return getLiteralType(name.text); case 146 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(element.name); + var nameType = checkComputedPropertyName(name); if (isTypeAssignableToKind(nameType, 1536 /* ESSymbolLike */)) { return nameType; } @@ -43188,7 +43253,7 @@ var ts; node.kind === 156 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - var propertyType = getTypeOfNode(node); + var propertyType = getTypeOfNode(node); // TODO: GH#18217 return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); @@ -43423,7 +43488,7 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); // TODO: GH#18217 while (typeArguments_1.length > typeParameters.length) { typeArguments_1.pop(); } @@ -43742,6 +43807,8 @@ var ts; case 155 /* GetAccessor */: case 156 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); } } /** @@ -43765,8 +43832,7 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); invocationErrorRecovery(apparentType, 0 /* Call */); @@ -43830,7 +43896,7 @@ var ts; return ts.length(sigs) ? sigs[0] : unknownSignature; }) || unknownSignature; } - ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } /** * Resolve a signature of a given call-like expression. @@ -43870,7 +43936,7 @@ var ts; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; - return symbol && symbol.members !== undefined; + return !!symbol && symbol.members !== undefined; } return false; } @@ -44053,7 +44119,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -44106,6 +44172,7 @@ var ts; if (node.keywordToken === 91 /* ImportKeyword */) { return checkImportMetaProperty(node); } + return ts.Debug.assertNever(node.keywordToken); } function checkNewTargetMetaProperty(node) { var container = ts.getNewTargetContainer(node); @@ -44185,9 +44252,9 @@ var ts; } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. - var parameter = ts.lastOrUndefined(signature.parameters); + var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + var contextualParameterType = getTypeOfSymbol(ts.last(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } @@ -44607,7 +44674,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 245 /* NamespaceImport */; + return !!declaration && declaration.kind === 245 /* NamespaceImport */; } } } @@ -44731,15 +44798,15 @@ var ts; if (strict && source.flags & (1 /* Any */ | 2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */)) { return false; } - return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || - (kind & 34 /* StringLike */ && isTypeAssignableTo(source, stringType)) || - (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || - (kind & 2048 /* Void */ && isTypeAssignableTo(source, voidType)) || - (kind & 16384 /* Never */ && isTypeAssignableTo(source, neverType)) || - (kind & 8192 /* Null */ && isTypeAssignableTo(source, nullType)) || - (kind & 4096 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || - (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || - (kind & 134217728 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + return !!(kind & 84 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 34 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 136 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 2048 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 16384 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 8192 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 4096 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 512 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 134217728 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { return source.flags & 131072 /* Union */ ? @@ -44747,7 +44814,7 @@ var ts; isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -44784,7 +44851,7 @@ var ts; if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 1536 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { + if (!(rightType.flags & 1 /* Any */ || isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -45150,6 +45217,8 @@ var ts; error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; + default: + return ts.Debug.fail(); } function checkSpecialAssignment(left, right) { var special = ts.getSpecialPropertyAssignmentKind(left.parent); @@ -45243,7 +45312,9 @@ var ts; } } var func = ts.getContainingFunction(node); - var functionFlags = func ? ts.getFunctionFlags(func) : 0 /* Normal */; + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); if (!(functionFlags & 1 /* Generator */)) { // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. return anyType; @@ -45262,7 +45333,7 @@ var ts; } } var isAsync = (functionFlags & 2 /* Async */) !== 0; - var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. @@ -45355,14 +45426,6 @@ var ts; } return widened; } - function isTypeParameterWithKeyofConstraint(type) { - if (type.flags & 32768 /* TypeParameter */) { - var constraintDeclaration = getConstraintDeclaration(type); - return constraintDeclaration && constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */; - } - return false; - } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 393216 /* UnionOrIntersection */) { @@ -45374,19 +45437,17 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return isTypeParameterWithKeyofConstraint(contextualType) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */ | 64 /* NumberLiteral */ | 1024 /* UniqueESSymbol */) || - constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 2 /* String */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + maybeTypeOfKind(constraint, 4 /* Number */) && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 512 /* ESSymbol */) && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + return !!(contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || contextualType.flags & 64 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || contextualType.flags & 128 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */); + contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */)); } return false; } @@ -45687,7 +45748,8 @@ var ts; } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), // TODO: GH#18217 + node.type, /*headMessage*/ undefined, leadingError); } } @@ -45839,20 +45901,21 @@ var ts; else { var isStatic = ts.hasModifier(member, 32 /* Static */); var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { switch (member.kind) { case 155 /* GetAccessor */: - addName(names, member.name, memberName, 1 /* Getter */); + addName(names, name, memberName, 1 /* Getter */); break; case 156 /* SetAccessor */: - addName(names, member.name, memberName, 2 /* Setter */); + addName(names, name, memberName, 2 /* Setter */); break; case 151 /* PropertyDeclaration */: - addName(names, member.name, memberName, 3 /* Property */); + addName(names, name, memberName, 3 /* Property */); break; case 153 /* MethodDeclaration */: - addName(names, member.name, memberName, 4 /* Method */); + addName(names, name, memberName, 4 /* Method */); break; } } @@ -45916,13 +45979,14 @@ var ts; var member = _a[_i]; if (member.kind === 150 /* PropertySignature */) { var memberName = void 0; - switch (member.name.kind) { + var name = member.name; + switch (name.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - memberName = member.name.text; + memberName = name.text; break; case 71 /* Identifier */: - memberName = ts.idText(member.name); + memberName = ts.idText(name); break; default: continue; @@ -46179,7 +46243,7 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -46578,7 +46642,7 @@ var ts; case 247 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: - ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); } } } @@ -46611,7 +46675,7 @@ var ts; if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 if (isTypeAny(thenFunction)) { return undefined; } @@ -46732,7 +46796,8 @@ var ts; var thenFunction = getTypeOfPropertyOfType(type, "then"); if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); + if (!diagnosticMessage) + return ts.Debug.fail(); error(errorNode, diagnosticMessage); } return undefined; @@ -46777,7 +46842,7 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); // TODO: GH#18217 var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (returnType === unknownType) { @@ -46852,19 +46917,23 @@ var ts; break; case 148 /* Parameter */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; case 151 /* PropertyDeclaration */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 153 /* MethodDeclaration */: case 155 /* GetAccessor */: case 156 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); + var methodType = getTypeOfNode(node.parent); // TODO: GH#18217 var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; + default: + return ts.Debug.fail(); } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } @@ -47199,13 +47268,6 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 231 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 147 /* TypeParameter */) { - return; - } - } var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); } @@ -47283,6 +47345,7 @@ var ts; // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. var unusedImports = ts.createMap(); var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); nodeWithLocals.locals.forEach(function (local) { // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. // If it's a type parameter merged with a parameter, check if the parameter-side is used. @@ -47303,6 +47366,11 @@ var ts; addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + if (!isIdentifierThatStartsWithUnderScore(declaration.name) || !ts.isForInOrOfStatement(declaration.parent.parent)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + } else { var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); if (parameter) { @@ -47320,47 +47388,74 @@ var ts; unusedImports.forEach(function (_a) { var importClause = _a[0], unuseds = _a[1]; var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 245 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { var unused = unuseds_1[_i]; errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } } - else if (unuseds.length === 1) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))); - } - else { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); - } }); unusedDestructures.forEach(function (_a) { var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; - if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) { + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 231 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 232 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } + else { + addDiagnostic(kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + } + } + else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); } } - else if (bindingElements.length === 1) { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier)))); + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 213 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { - addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + } } }); } + function bindingNameText(name) { + switch (name.kind) { + case 71 /* Identifier */: + return ts.idText(name); + case 180 /* ArrayBindingPattern */: + case 179 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); + } + } function isImportedDeclaration(node) { return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */; } function importClauseFromImported(decl) { return decl.kind === 244 /* ImportClause */ ? decl : decl.kind === 245 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } - function forEachImportedDeclaration(importClause, cb) { - var defaultName = importClause.name, namedBindings = importClause.namedBindings; - return (defaultName && cb(importClause)) || - namedBindings && (namedBindings.kind === 245 /* NamespaceImport */ ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); - } function checkBlock(node) { // Grammar checking for SyntaxKind.Block if (node.kind === 212 /* Block */) { @@ -47426,6 +47521,7 @@ var ts; } return true; } + return false; }); } function checkIfNewTargetIsCapturedInEnclosingScope(node) { @@ -47440,6 +47536,7 @@ var ts; } return true; } + return false; }); } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -47640,7 +47737,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); @@ -47885,7 +47982,7 @@ var ts; } // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (rightType === neverType || !isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { + if (rightType === neverType || !(rightType.flags & 1 /* Any */ || isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */))) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); @@ -47918,7 +48015,7 @@ var ts; */ function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { if (inputType === neverType) { - reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 return undefined; } var uplevelIteration = languageVersion >= 2 /* ES2015 */; @@ -48068,11 +48165,11 @@ var ts; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); if (isTypeAny(methodType)) { return undefined; } - var signatures = methodType && getSignaturesOfType(methodType, 0 /* Call */); + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; if (!ts.some(signatures)) { if (errorNode) { // only report on the first error @@ -48205,7 +48302,7 @@ var ts; var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { // Grammar checking @@ -48330,6 +48427,7 @@ var ts; grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } + return false; }); } // ensure that label is unique @@ -48389,8 +48487,8 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; // Only process instance properties with computed names here. @@ -48414,7 +48512,7 @@ var ts; errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { @@ -48509,8 +48607,8 @@ var ts; if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { // Report an error on every conflicting declaration. var name = symbolToString(symbol); - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -48519,8 +48617,8 @@ var ts; function areTypeParametersIdentical(declarations, targetParameters) { var maxTypeArgumentCount = ts.length(targetParameters); var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; // If this declaration has too few or too many type parameters, we report an error var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); var numTypeParameters = sourceParameters.length; @@ -48741,7 +48839,7 @@ var ts; if (base.flags & 4194304 /* Prototype */) { continue; } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { @@ -48770,7 +48868,7 @@ var ts; // either base or derived property is private - not override, skip it continue; } - if (isPrototypeProperty(base) && isPrototypeProperty(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; } @@ -49015,7 +49113,11 @@ var ts; case 190 /* ParenthesizedExpression */: return evaluate(expr.expression); case 71 /* Identifier */: - return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); case 185 /* ElementAccessExpression */: case 184 /* PropertyAccessExpression */: var ex = expr; @@ -49115,8 +49217,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; if ((declaration.kind === 234 /* ClassDeclaration */ || (declaration.kind === 233 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304 /* Ambient */)) { @@ -49169,7 +49271,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 && !inAmbientContext - && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -49300,7 +49402,7 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (ts.nodeIsMissing(moduleName)) { + if (!moduleName || ts.nodeIsMissing(moduleName)) { // Should be a parse error. return false; } @@ -49558,8 +49660,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -49582,11 +49684,11 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var tags = _a[_i].tags; - ts.forEach(tags, checkSourceElement); - } + if (ts.isInJavaScriptFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); } var kind = node.kind; if (cancellationToken) { @@ -49759,7 +49861,7 @@ var ts; if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } - var paramTag = parent.parent; + var paramTag = node.parent.parent; if (!ts.isJSDocParameterTag(paramTag)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); return; @@ -49777,8 +49879,8 @@ var ts; function getTypeFromJSDocVariadicType(node) { var type = getTypeFromTypeNode(node.type); var parent = node.parent; - var paramTag = parent.parent; - if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); if (host_1) { @@ -49817,8 +49919,8 @@ var ts; } } function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; + for (var _i = 0, _a = deferredNodes; _i < _a.length; _i++) { + var node = _a[_i]; switch (node.kind) { case 191 /* FunctionExpression */: case 192 /* ArrowFunction */: @@ -49845,9 +49947,9 @@ var ts; function unusedIsError(kind) { switch (kind) { case 0 /* Local */: - return compilerOptions.noUnusedLocals; + return !!compilerOptions.noUnusedLocals; case 1 /* Parameter */: - return compilerOptions.noUnusedParameters; + return !!compilerOptions.noUnusedParameters; default: return ts.Debug.assertNever(kind); } @@ -50041,22 +50143,22 @@ var ts; case 236 /* TypeAliasDeclaration */: case 237 /* EnumDeclaration */: return true; + default: + return false; } } // True if the given identifier is part of a type reference - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 145 /* QualifiedName */) { + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 145 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 161 /* TypeReference */; + return node.parent.kind === 161 /* TypeReference */; } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 184 /* PropertyAccessExpression */) { + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 184 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */; + return node.parent.kind === 206 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -50088,10 +50190,10 @@ var ts; nodeOnRightSide = nodeOnRightSide.parent; } if (nodeOnRightSide.parent.kind === 242 /* ImportEqualsDeclaration */) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } if (nodeOnRightSide.parent.kind === 248 /* ExportAssignment */) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; } @@ -50229,25 +50331,27 @@ var ts; if (node.kind === 273 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } + var parent = node.parent; + var grandParent = parent.parent; if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(node.parent); + return getSymbolOfNode(parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); + return getSymbolOfNode(parent.parent); } if (node.kind === 71 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 181 /* BindingElement */ && - node.parent.parent.kind === 179 /* ObjectBindingPattern */ && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); + else if (parent.kind === 181 /* BindingElement */ && + grandParent.kind === 179 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; @@ -50297,10 +50401,10 @@ var ts; // falls through case 8 /* NumericLiteral */: // index access - var objectType = ts.isElementAccessExpression(node.parent) - ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined - : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) - ? getTypeFromTypeNode(node.parent.parent.objectType) + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79 /* DefaultKeyword */: @@ -50405,14 +50509,14 @@ var ts; // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { if (expr.parent.kind === 269 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern ts.Debug.assert(expr.parent.kind === 182 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); // TODO: GH#18217 } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -50483,9 +50587,9 @@ var ts; return target; } // Emitter support - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var isPropertyName_1 = node.parent.kind === 184 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; @@ -50518,13 +50622,12 @@ var ts; } } function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum // declaration, we need to start resolution at the declaration's container. @@ -50558,8 +50661,8 @@ var ts; } // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value @@ -50614,9 +50717,9 @@ var ts; // When resolved as an expression identifier, if the given node references a nested block scoped entity with // a name that either hides an existing name or might hide it when compiled downlevel, // return the declaration of that entity. Otherwise, return undefined. - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { @@ -50628,8 +50731,8 @@ var ts; } // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); if (node) { var symbol = getSymbolOfNode(node); if (symbol) { @@ -50648,7 +50751,7 @@ var ts; return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case 249 /* ExportDeclaration */: var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); case 248 /* ExportAssignment */: return node.expression && node.expression.kind === 71 /* Identifier */ @@ -50657,8 +50760,8 @@ var ts; } return false; } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); if (node === undefined || node.parent.kind !== 273 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; @@ -50673,11 +50776,11 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return target.flags & 67216319 /* Value */ && + return !!(target.flags & 67216319 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { if (ts.isAliasSymbolDeclaration(node)) { @@ -50685,14 +50788,14 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } - var target = getSymbolLinks(symbol).target; + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } } if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); } return false; } @@ -50719,10 +50822,10 @@ var ts; return false; } function isRequiredInitializedParameter(parameter) { - return strictNullChecks && + return !!strictNullChecks && !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && - parameter.initializer && + !!parameter.initializer && !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { @@ -50732,7 +50835,7 @@ var ts; ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + return getNodeLinks(node).flags || 0; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -50761,11 +50864,11 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 65536 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 65536 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } - function getTypeReferenceSerializationKind(typeName, location) { + function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. - typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); if (!typeName) return ts.TypeReferenceSerializationKind.Unknown; if (location) { @@ -50789,7 +50892,7 @@ var ts; } // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; + return ts.TypeReferenceSerializationKind.Unknown; } var type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { @@ -50826,8 +50929,8 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function createTypeOfDeclaration(declaration, enclosingDeclaration, flags, tracker, addUndefined) { - declaration = ts.getParseTreeNode(declaration, ts.isVariableLikeOrAccessor); + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); if (!declaration) { return ts.createToken(119 /* AnyKeyword */); } @@ -50845,16 +50948,16 @@ var ts; } return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function createReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, tracker) { - signatureDeclaration = ts.getParseTreeNode(signatureDeclaration, ts.isFunctionLike); + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); if (!signatureDeclaration) { return ts.createToken(119 /* AnyKeyword */); } var signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function createTypeOfExpression(expr, enclosingDeclaration, flags, tracker) { - expr = ts.getParseTreeNode(expr, ts.isExpression); + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); if (!expr) { return ts.createToken(119 /* AnyKeyword */); } @@ -50880,9 +50983,9 @@ var ts; } return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); if (reference) { var symbol = getReferencedValueSymbol(reference); if (symbol) { @@ -50940,7 +51043,7 @@ var ts; }, getNodeCheckFlags: function (node) { node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; + return node ? getNodeCheckFlags(node) : 0; }, isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, @@ -50953,8 +51056,8 @@ var ts; createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, collectLinkedAliases: collectLinkedAliases, @@ -50967,14 +51070,14 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - isLateBound: function (node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { - accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; @@ -51069,7 +51172,7 @@ var ts; } function getExternalModuleFileFromDeclaration(declaration) { var specifier = declaration.kind === 238 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } @@ -51104,7 +51207,7 @@ var ts; }); } } - // We do global augmentations seperately from module augmentations (and before creating global types) because they + // We do global augmentations separately from module augmentations (and before creating global types) because they // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require // checking for an export or property on the module (if export=) which, in turn, can fall back to the @@ -51199,7 +51302,7 @@ var ts; case 16384 /* AsyncValues */: return "__asyncValues"; case 32768 /* ExportStar */: return "__exportStar"; case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; - default: ts.Debug.fail("Unrecognized helper"); + default: return ts.Debug.fail("Unrecognized helper"); } } function resolveHelpersModule(node, errorNode) { @@ -51407,7 +51510,7 @@ var ts; return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); @@ -51415,7 +51518,7 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); } - return; + return false; } else if ((node.kind === 243 /* ImportDeclaration */ || node.kind === 242 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); @@ -51429,6 +51532,7 @@ var ts; if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } + return false; } /** * true | false: Early return this value from checkGrammarModifiers. @@ -51499,6 +51603,7 @@ var ts; if (list && list.hasTrailingComma) { return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); } + return false; } function checkGrammarTypeParameterList(typeParameters, file) { if (typeParameters && typeParameters.length === 0) { @@ -51506,6 +51611,7 @@ var ts; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); } + return false; } function checkGrammarParameterList(parameters) { var seenOptionalParameter = false; @@ -51597,6 +51703,7 @@ var ts; if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } + return false; } function checkGrammarIndexSignature(node) { // Prevent cascading error by short-circuit @@ -51609,6 +51716,7 @@ var ts; var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); } + return false; } function checkGrammarTypeArguments(node, typeArguments) { return checkGrammarForDisallowedTrailingComma(typeArguments) || @@ -51623,6 +51731,7 @@ var ts; } } } + return false; } function checkGrammarArguments(args) { return checkGrammarForOmittedArgument(args); @@ -51636,7 +51745,7 @@ var ts; var listType = ts.tokenToString(node.token); return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } - return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + return ts.some(types, checkGrammarExpressionWithTypeArguments); } function checkGrammarExpressionWithTypeArguments(node) { return checkGrammarTypeArguments(node, node.typeArguments); @@ -51701,6 +51810,7 @@ var ts; if (computedPropertyName.expression.kind === 199 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } + return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { @@ -51716,9 +51826,7 @@ var ts; } } function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } + return !!questionToken && grammarErrorOnNode(questionToken, message); } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; @@ -51746,7 +51854,7 @@ var ts; } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 153 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); @@ -51781,7 +51889,7 @@ var ts; currentKind = 4 /* SetAccessor */; break; default: - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -51914,6 +52022,7 @@ var ts; } } } + return false; } /** Does the accessor have the right number of parameters? * A get accessor has no parameters or a single `this` parameter. @@ -52140,6 +52249,7 @@ var ts; } } } + return false; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 71 /* Identifier */) { @@ -52156,6 +52266,7 @@ var ts; } } } + return false; } function checkGrammarVariableDeclarationList(declarationList) { var declarations = declarationList.declarations; @@ -52165,6 +52276,7 @@ var ts; if (!declarationList.declarations.length) { return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } + return false; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { @@ -52216,6 +52328,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); @@ -52223,6 +52336,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorOnNode(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -52230,6 +52344,7 @@ var ts; diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; } + return false; } function checkGrammarConstructorTypeParameters(node) { var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); @@ -52308,6 +52423,7 @@ var ts; } } } + return false; } function checkGrammarSourceFile(node) { return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); @@ -52341,6 +52457,7 @@ var ts; // Debug.assert(isStatement(node.parent)); } } + return false; } function checkGrammarNumericLiteral(node) { // Grammar checking @@ -52361,6 +52478,7 @@ var ts; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } + return false; } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -52369,6 +52487,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } + return false; } function getAmbientModules() { if (!ambientModulesCache) { @@ -52398,6 +52517,7 @@ var ts; if (ts.isSpreadElement(nodeArguments[0])) { return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); } + return false; } } ts.createTypeChecker = createTypeChecker; @@ -52482,7 +52602,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). if (node === undefined) { - return undefined; + return node; } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; @@ -52587,7 +52707,6 @@ var ts; return name; } ts.createUniqueName = createUniqueName; - /** Create a unique name based on the supplied text. */ function createOptimisticUniqueName(text) { var name = createIdentifier(text); name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; @@ -53290,7 +53409,7 @@ var ts; function createPropertyAccess(expression, name) { var node = createSynthesizedNode(184 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); - node.name = asName(name); + node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); return node; } @@ -54013,6 +54132,7 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { + if (flags === void 0) { flags = 0 /* None */; } var node = createSynthesizedNode(232 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); @@ -54134,6 +54254,7 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { + if (flags === void 0) { flags = 0 /* None */; } var node = createSynthesizedNode(238 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); @@ -54564,7 +54685,7 @@ var ts; ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { var node = createSynthesizedNode(271 /* SpreadAssignment */); - node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } ts.createSpreadAssignment = createSpreadAssignment; @@ -54635,6 +54756,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -54861,6 +54984,7 @@ var ts; return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); } ts.createExternalModuleExport = createExternalModuleExport; + // Utilities function asName(name) { return ts.isString(name) ? createIdentifier(name) : name; } @@ -55391,7 +55515,7 @@ var ts; // Utilities function createForOfBindingStatement(node, boundValue) { if (ts.isVariableDeclarationList(node)) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); + var firstDeclaration = ts.first(node.declarations); var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, /*typeNode*/ undefined, boundValue); return ts.setTextRange(ts.createVariableStatement( @@ -55448,6 +55572,7 @@ var ts; } } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } var callee = skipOuterExpressions(expression, 7 /* All */); var thisArg; var target; @@ -55539,7 +55664,7 @@ var ts; switch (property.kind) { case 155 /* GetAccessor */: case 156 /* SetAccessor */: - return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); case 269 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); case 270 /* ShorthandPropertyAssignment */: @@ -55558,7 +55683,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, - /*type*/ undefined, getAccessor.body); + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); @@ -55569,7 +55695,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, - /*type*/ undefined, setAccessor.body); + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); @@ -55600,7 +55727,8 @@ var ts; return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, - /*type*/ undefined, method.body), + /*type*/ undefined, method.body // TODO: GH#18217 + ), /*location*/ method), /*original*/ method)), /*location*/ method), @@ -55683,6 +55811,7 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { var name = ts.getMutableClone(nodeName); @@ -55726,7 +55855,7 @@ var ts; function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); ts.setTextRange(qualifiedName, name); - var emitFlags; + var emitFlags = 0; if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -55741,7 +55870,8 @@ var ts; } ts.convertToFunctionBody = convertToFunctionBody; function convertFunctionDeclarationToExpression(node) { - ts.Debug.assert(!!node.body); + if (!node.body) + return ts.Debug.fail(); var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); @@ -55801,15 +55931,9 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - /** - * Add just the custom prologue-directives into target statement-array. - * The function needs to be called during each transformation step. - * This function needs to be called whenever we transform the statement - * list of a source file, namespace, or function-like body. - */ function addCustomPrologue(target, source, statementOffset, visitor) { var numStatements = source.length; - while (statementOffset < numStatements) { + while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); @@ -56383,7 +56507,7 @@ var ts; * Otherwise, a new StringLiteral node representing the module name will be returned. */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { - var moduleName = ts.getExternalModuleName(importNode); + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 if (moduleName.kind === 9 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) @@ -56441,8 +56565,9 @@ var ts; // `1` in `({ a: b = 1 } = ...)` // `1` in `({ a: {b} = 1 } = ...)` // `1` in `({ a: [b] = 1 } = ...)` - return ts.isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true) - ? bindingElement.initializer.right + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right : undefined; } if (ts.isShorthandPropertyAssignment(bindingElement)) { @@ -57522,7 +57647,7 @@ var ts; } return ts.isNodeArray(statements) ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) - : ts.prependRange(statements, declarations); + : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -57680,7 +57805,7 @@ var ts; return ts.some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { - return e.propertyName && e.propertyName.escapedText === "default" /* Default */; + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; } function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; @@ -57715,7 +57840,7 @@ var ts; ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) - return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -57942,7 +58067,7 @@ var ts; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: true, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -58003,7 +58128,7 @@ var ts; } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; function bindingOrAssignmentElementAssignsToName(element, escapedName) { - var target = ts.getTargetOfBindingOrAssignmentElement(element); + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isBindingOrAssignmentPattern(target)) { return bindingOrAssignmentPatternAssignsToName(target, escapedName); } @@ -58034,13 +58159,14 @@ var ts; * @param level Indicates the extent to which flattening should occur. */ function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } var pendingExpressions; var pendingDeclarations = []; var declarations = []; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: hoistTempVariables, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -58068,7 +58194,7 @@ var ts; } else { context.hoistVariableDeclaration(temp); - var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + var pendingDeclaration = ts.last(pendingDeclarations); pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); pendingDeclaration.value = temp; @@ -58122,7 +58248,7 @@ var ts; value = ts.createVoidZero(); } } - var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } @@ -58130,7 +58256,7 @@ var ts; flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } else { - flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 } } /** @@ -58182,7 +58308,7 @@ var ts; flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); bindingElements = undefined; } - var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); } } @@ -58956,7 +59082,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, context.endLexicalEnvironment()); + ts.prependStatements(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -60043,7 +60169,8 @@ var ts; * @param node The type reference node. */ function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); var temp = ts.createTempVariable(hoistVariableDeclaration); @@ -60069,8 +60196,9 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } /** @@ -60579,7 +60707,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -60628,7 +60756,7 @@ var ts; * @param node The module declaration node. */ function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -60820,7 +60948,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -61219,7 +61347,7 @@ var ts; // constructor references in static property initializers. var declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { - var classAlias = classAliases[declaration.id]; + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { var clone_1 = ts.getSynthesizedClone(classAlias); ts.setSourceMapRange(clone_1, node); @@ -61421,7 +61549,7 @@ var ts; } function visitCatchClauseInAsyncBody(node) { var catchClauseNames = ts.createUnderscoreEscapedMap(); - recordDeclarationName(node.variableDeclaration, catchClauseNames); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 // names declared in a catch variable are block scoped var catchClauseUnshadowedNames; catchClauseNames.forEach(function (_, escapedName) { @@ -61461,8 +61589,9 @@ var ts; : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } function visitForStatementInAsyncBody(node) { - return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) - ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } /** @@ -61554,10 +61683,10 @@ var ts; } } function isVariableDeclarationListWithCollidingName(node) { - return node + return !!node && ts.isVariableDeclarationList(node) && !(node.flags & 3 /* BlockScoped */) - && ts.forEach(node.declarations, collidesWithParameterName); + && node.declarations.some(collidesWithParameterName); } function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { hoistVariableDeclarationList(node); @@ -61629,7 +61758,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -62228,7 +62357,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -62256,7 +62385,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependRange(statements, leadingStatements); + ts.prependStatements(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -62545,14 +62674,16 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + 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(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -63209,7 +63340,7 @@ var ts; hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 && node.kind === 224 /* ReturnStatement */ && !node.expression; } @@ -63349,7 +63480,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -63424,7 +63555,8 @@ var ts; (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; - if (!node.label) { + var label = node.label; + if (!label) { if (node.kind === 223 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; @@ -63437,12 +63569,12 @@ var ts; } else { if (node.kind === 223 /* BreakStatement */) { - labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(node.label), labelMarker); + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } else { - labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(node.label), labelMarker); + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -63603,7 +63735,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -63661,7 +63793,7 @@ var ts; // `super` call. // If this is the case, we do not include the synthetic `...args` parameter and // will instead use the `arguments` object in ES5/3. - return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } /** @@ -63697,7 +63829,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -63716,7 +63848,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -64163,7 +64295,7 @@ var ts; // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); - ts.setSourceMapRange(target, firstAccessor.name); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); ts.setSourceMapRange(propertyName, firstAccessor.name); @@ -64359,7 +64491,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependRange(statements, lexicalEnvironment); + ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { @@ -64497,13 +64629,12 @@ var ts; ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); if (node.transformFlags & 8388608 /* ContainsBindingPattern */ - && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); if (firstDeclaration) { - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); } } return declarationList; @@ -64657,11 +64788,12 @@ var ts; } function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { var statements = []; - if (ts.isVariableDeclarationList(node.initializer)) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { if (node.initializer.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - var firstOriginalDeclaration = ts.firstOrUndefined(node.initializer.declarations); + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { // This works whether the declaration is a var, let, or const. // It will use rhsIterationValue _a[_i] as the initializer. @@ -64670,9 +64802,7 @@ var ts; ts.setOriginalNode(declarationList, node.initializer); // Adjust the source map range for the first declaration to align with the old // emitter. - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); statements.push(ts.createVariableStatement( /*modifiers*/ undefined, declarationList)); } @@ -64683,20 +64813,20 @@ var ts; /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), /*type*/ undefined, boundValue) - ]), ts.moveRangePos(node.initializer, -1)), node.initializer)), ts.moveRangeEnd(node.initializer, -1))); + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); } } else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. - var assignment = ts.createAssignment(node.initializer, boundValue); + var assignment = ts.createAssignment(initializer, boundValue); if (ts.isDestructuringAssignment(assignment)) { ts.aggregateTransformFlags(assignment); statements.push(ts.createStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); } else { - assignment.end = node.initializer.end; - statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); } } if (convertedLoopBodyStatements) { @@ -64940,7 +65070,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependRange(statements_4, lexicalEnvironment); + ts.prependStatements(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -65178,7 +65308,7 @@ var ts; case 156 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; case 153 /* MethodDeclaration */: @@ -65340,7 +65470,7 @@ var ts; function visitArrayLiteralExpression(node) { if (node.transformFlags & 64 /* ES2015 */) { // We are here because we contain a SpreadElementExpression. - return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } return ts.visitEachChild(node, visitor, context); } @@ -65395,11 +65525,11 @@ var ts; var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); // The class statements are the statements generated by visiting the first statement with initializer of the // body (1), while all other statements are added to remainingStatements (2) - var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; }; + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); - var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); // We know there is only one variable declaration here as we verified this in an // earlier call to isTypeScriptClassWrapper var variable = varStatement.declarationList.declarations[0]; @@ -65885,14 +66015,13 @@ var ts; * @param node An original source tree node. */ function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { + switch (node.parent.kind) { case 181 /* BindingElement */: case 234 /* ClassDeclaration */: case 237 /* EnumDeclaration */: case 231 /* VariableDeclaration */: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); } return false; } @@ -66123,7 +66252,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -66308,6 +66437,7 @@ var ts; case 4 /* Yield */: return "yield"; case 5 /* YieldStar */: return "yield*"; case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 } } function transformGenerators(context) { @@ -66615,7 +66745,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -66671,13 +66801,14 @@ var ts; * @param node The node to visit. */ function visitBinaryExpression(node) { - switch (ts.getExpressionAssociativity(node)) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { case 0 /* Left */: return visitLeftAssociativeBinaryExpression(node); case 1 /* Right */: return visitRightAssociativeBinaryExpression(node); default: - ts.Debug.fail("Unknown associativity."); + return ts.Debug.assertNever(assoc); } } function isCompoundAssignment(kind) { @@ -67685,7 +67816,7 @@ var ts; beginExceptionBlock(); transformAndEmitEmbeddedStatement(node.tryBlock); if (node.catchClause) { - beginCatchBlock(node.catchClause.variableDeclaration); + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 transformAndEmitEmbeddedStatement(node.catchClause.block); } if (node.finallyBlock) { @@ -67699,7 +67830,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -67800,7 +67931,8 @@ var ts; */ function endBlock() { var block = peekBlock(); - ts.Debug.assert(block !== undefined, "beginBlock was never called."); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); var index = blockActions.length; blockActions[index] = 1 /* Close */; blockOffsets[index] = operations ? operations.length : 0; @@ -68133,7 +68265,7 @@ var ts; * @param label A label. */ function createLabel(label) { - if (label > 0) { + if (label !== undefined && label > 0) { if (labelExpressions === undefined) { labelExpressions = []; } @@ -68851,7 +68983,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -69045,7 +69177,7 @@ var ts; if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { return undefined; } - var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 var expr = getHelperExpressionForImport(node, name); if (expr === name) { return undefined; @@ -69074,7 +69206,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependRange(statements, endLexicalEnvironment()); + ts.prependStatements(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -70343,8 +70475,8 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependRange(statements, endLexicalEnvironment()); - var exportStarFunction = addExportStarIfNeeded(statements); + ts.prependStatements(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), ts.createPropertyAssignment("execute", ts.createFunctionExpression( @@ -70480,7 +70612,7 @@ var ts; var statements = []; for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { case 243 /* ImportDeclaration */: if (!entry.importClause) { @@ -70566,7 +70698,7 @@ var ts; function visitImportDeclaration(node) { var statements; if (node.importClause) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -70586,7 +70718,7 @@ var ts; function visitImportEqualsDeclaration(node) { ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); var statements; - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); @@ -71087,7 +71219,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -71131,9 +71263,6 @@ var ts; * @param node The node to visit. */ function visitForInitializer(node) { - if (!node) { - return node; - } if (shouldHoistForInitializer(node)) { var expressions = void 0; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { @@ -71817,7 +71946,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 231 /* VariableDeclaration */ || node.kind === 181 /* BindingElement */) { @@ -71952,7 +72081,7 @@ var ts; ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; break; default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); } return { diagnosticMessage: diagnosticMessage, @@ -72021,7 +72150,7 @@ var ts; ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; default: - ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); } } function getTypeParameterConstraintVisibilityError() { @@ -72059,7 +72188,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); } return { diagnosticMessage: diagnosticMessage, @@ -72231,7 +72360,7 @@ var ts; var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) - return; // Omit declaration files from bundle results, too + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -72463,7 +72592,7 @@ var ts; } if (ts.isBindingPattern(elem.name)) { // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible - return ts.forEach(elem.name.elements, getBindingNameVisible); + return ts.some(elem.name.elements, getBindingNameVisible); } else { return resolver.isDeclarationVisible(elem); @@ -72471,11 +72600,11 @@ var ts; } function updateParamsList(node, params, modifierMask) { if (ts.hasModifier(node, 8 /* Private */)) { - return undefined; + return undefined; // TODO: GH#18217 } var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); if (!newParams) { - return undefined; + return undefined; // TODO: GH#18217 } return ts.createNodeArray(newParams, params.hasTrailingComma); } @@ -72505,7 +72634,7 @@ var ts; } function rewriteModuleSpecifier(parent, input) { if (!input) - return; + return undefined; // TODO: GH#18217 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 238 /* ModuleDeclaration */ && parent.kind !== 178 /* ImportType */); if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -72674,7 +72803,9 @@ var ts; case 154 /* Constructor */: { var isPrivate = ts.hasModifier(input, 8 /* Private */); // A constructor declaration may not have a type annotation - var ctor = ts.createSignatureDeclaration(154 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + var ctor = ts.createSignatureDeclaration(154 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), /*type*/ undefined); ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); return cleanup(ctor); @@ -72874,7 +73005,7 @@ var ts; needsDeclare = false; ts.visitNode(inner, visitDeclarationStatements); // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) - var id = "" + ts.getOriginalNodeId(inner); + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); return cleanup(ts.updateModuleDeclaration(input, @@ -72924,7 +73055,7 @@ var ts; var extendsClause_1 = ts.getClassExtendsHeritageClauseElement(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression - var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -72943,7 +73074,7 @@ var ts; return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); })); return [statement, cleanup(ts.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); @@ -73731,7 +73862,7 @@ var ts; } if (node) { var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.sourceMapRange; var _a = range || node, pos = _a.pos, end = _a.end; var source = range && range.source; @@ -73779,7 +73910,7 @@ var ts; return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { @@ -73826,7 +73957,7 @@ var ts; */ function getText() { if (disabled) { - return; + return undefined; // TODO: GH#18217 } encodeLastRecordedSourceMapSpan(); return JSON.stringify({ @@ -73844,7 +73975,7 @@ var ts; */ function getSourceMappingURL() { if (disabled) { - return; + return undefined; // TODO: GH#18217 } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url @@ -73905,7 +74036,7 @@ var ts; var currentLineMap; var detachedCommentsInfo; var hasWrittenComment = false; - var disabled = printerOptions.removeComments; + var disabled = !!printerOptions.removeComments; return { reset: reset, setWriter: setWriter, @@ -73923,7 +74054,7 @@ var ts; if (node) { hasWrittenComment = false; var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. @@ -74211,11 +74342,11 @@ var ts; detachedCommentsInfo = undefined; } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { // get the leading comments from detachedPos - var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -74270,6 +74401,7 @@ var ts; * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. */ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { @@ -74300,7 +74432,7 @@ var ts; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension); + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { @@ -74371,7 +74503,7 @@ var ts; emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, - sourceMaps: sourceMapDataList + sourceMaps: sourceMapDataList, }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -74478,7 +74610,7 @@ var ts; ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); // Write bundled offset information if applicable if (bundleInfoPath) { bundleInfo.totalLength = writer.getTextPos(); @@ -74662,7 +74794,7 @@ var ts; } } function setWriter(output) { - writer = output; + writer = output; // TODO: GH#18217 comments.setWriter(output); } function reset() { @@ -74720,8 +74852,7 @@ var ts; return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assertDefined(onEmitNode); - onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); + ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); } function pipelineEmitWithComments(hint, node) { ts.Debug.assertDefined(emitNodeWithComments); @@ -74733,9 +74864,8 @@ var ts; pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assertDefined(onEmitSourceMapOfNode); ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */); - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); + ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { if (hint === 0 /* SourceFile */) @@ -75988,7 +76118,7 @@ var ts; writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emitIdentifierName(node.name); + emitIdentifierName(node.name); // TODO: GH#18217 emitSignatureAndBody(node, emitSignatureHead); } function emitBlockCallback(_hint, body) { @@ -76357,7 +76487,7 @@ var ts; } function emitJsxAttribute(node) { emit(node.name); - emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); @@ -76491,7 +76621,7 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) @@ -76719,7 +76849,7 @@ var ts; emitNodeList(emit, parentNode, children, format, start, count); } function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { switch (format & 28 /* DelimitersMask */) { @@ -76745,7 +76875,7 @@ var ts; if (isUndefined && format & 8192 /* OptionalIfUndefined */) { return; } - var isEmpty = isUndefined || start >= children.length || count === 0; + var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 16384 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -76758,6 +76888,7 @@ var ts; if (format & 7680 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -76777,7 +76908,7 @@ var ts; // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; - if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } @@ -76790,7 +76921,7 @@ var ts; } // Emit each child. var previousSibling = void 0; - var shouldDecreaseIndentAfterEmit = void 0; + var shouldDecreaseIndentAfterEmit = false; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -76868,6 +76999,7 @@ var ts; } if (format & 7680 /* BracketsMask */) { if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -77396,7 +77528,7 @@ var ts; * Generates a unique name for an ImportDeclaration or ExportDeclaration. */ function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 var baseName = ts.isStringLiteral(expr) ? ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); @@ -77458,7 +77590,7 @@ var ts; case 3 /* Unique */: return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); } - ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } /** * Gets the node from which a name should be generated. @@ -77921,8 +78053,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); - var mtimeBefore = ts.sys.getModifiedTime(fileName); + var hash = ts.sys.createHash(data); // TODO: GH#18217 + var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -77934,7 +78066,7 @@ var ts; } } ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); + var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -78005,7 +78137,7 @@ var ts; function formatDiagnostic(diagnostic, host) { 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 _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 var fileName = diagnostic.file.fileName; var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; @@ -78052,7 +78184,7 @@ var ts; var context_2 = ""; if (diagnostic.file) { var start = diagnostic.start, length_4 = diagnostic.length, file_9 = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; + var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 var _b = ts.getLineAndCharacterOfPosition(file_9, start + length_4), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file_9, file_9.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file_9.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_9.fileName; @@ -78196,8 +78328,7 @@ var ts; } ts.isProgramUptoDate = isProgramUptoDate; function getConfigFileParsingDiagnostics(configFileParseResult) { - return configFileParseResult.options.configFile ? - configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : configFileParseResult.errors; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; @@ -78228,9 +78359,9 @@ var ts; }; } function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { - var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; - var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram; + var oldProgram = createProgramOptions.oldProgram; var program; var files = []; var commonSourceDirectory; @@ -78257,7 +78388,7 @@ var ts; // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); - host = host || createCompilerHost(options); + var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHost(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); @@ -78285,7 +78416,7 @@ var ts; } else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -78293,7 +78424,7 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -78427,7 +78558,7 @@ var ts; } else if (options.composite) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -78548,7 +78679,7 @@ var ts; // `result[i]` is either a `ResolvedModuleFull` or a marker. // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; + result[i] = undefined; // TODO: GH#18217 } } else { @@ -78561,7 +78692,7 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same @@ -78657,7 +78788,7 @@ var ts; var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; } @@ -78843,7 +78974,7 @@ var ts; return nodes; } function isSourceFileFromExternalLibrary(file) { - return sourceFilesFoundSearchingNodeModules.get(file.path); + return !!sourceFilesFoundSearchingNodeModules.get(file.path); } function isSourceFileDefaultLibrary(file) { if (file.hasNoDefaultLib) { @@ -78859,7 +78990,7 @@ var ts; return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } } function getDiagnosticsProducingTypeChecker() { @@ -78912,7 +79043,8 @@ var ts; var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -79003,11 +79135,19 @@ var ts; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } } - return ts.filter(diagnostics, shouldReportDiagnostic); + return diagnostics; }); } /** @@ -79017,7 +79157,7 @@ var ts; var file = diagnostic.file, start = diagnostic.start; if (file) { var lineStarts = ts.getLineStarts(file); - var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 while (line > 0) { var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); @@ -79224,7 +79364,7 @@ var ts; if (cachedResult) { return cachedResult; } - var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 if (sourceFile) { if (!cache.perFile) { cache.perFile = ts.createMap(); @@ -79404,7 +79544,8 @@ var ts; } /** This has side effects through `findSourceFile`. */ function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -79496,7 +79637,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 redirectTargetsSet.set(fileFromPackageId.path, true); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -79591,7 +79732,7 @@ var ts; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 } else { // If we already resolved to this file, it must have been a secondary reference. Check file contents @@ -79601,7 +79742,8 @@ var ts; if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } } // don't overwrite previous resolution result @@ -79614,7 +79756,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 } if (saveResolution) { resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); @@ -79718,7 +79860,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(host, ref); // TODO: GH#18217 // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -79729,13 +79871,13 @@ var ts; return { commandLine: commandLine, sourceFile: sourceFile }; } function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); } function getDeclarationOutputDirectory(proj) { return proj.options.declarationDir || proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); + ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !options.strictNullChecks) { @@ -79990,9 +80132,9 @@ var ts; if (ts.isObjectLiteralExpression(pathProp.initializer)) { for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { var keyProps = _b[_a]; - if (ts.isArrayLiteralExpression(keyProps.initializer) && - keyProps.initializer.elements.length > valueIndex) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); needCompilerDiagnostic = false; } } @@ -80053,7 +80195,7 @@ var ts; if (_referencesArrayLiteralSyntax === undefined) { _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword if (options.configFile) { - var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { var prop = _a[_i]; if (ts.isArrayLiteralExpression(prop.initializer)) { @@ -80095,6 +80237,7 @@ var ts; return false; } programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + return false; // TODO: GH#18217 This function always returns `false`!` } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); @@ -80114,6 +80257,10 @@ var ts; if (out) { return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } // If --outDir, check if file is in that directory if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); @@ -80121,8 +80268,8 @@ var ts; if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); - return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts" /* Ts */)) || - !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx" /* Tsx */)); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); } return false; } @@ -80247,7 +80394,7 @@ var ts; if (!resolvedTypeReferenceDirective) { return; } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); @@ -80279,7 +80426,7 @@ var ts; for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var version_1 = sourceFile.version; - var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -80342,7 +80489,8 @@ var ts; return false; } var info = state.fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); + if (!info) + return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { @@ -80354,7 +80502,7 @@ var ts; latestSignature = computeHash(emitOutput.outputFiles[0].text); } else { - latestSignature = prevSignature; + latestSignature = prevSignature; // TODO: GH#18217 } } cacheToUpdateSignature.set(sourceFile.path, latestSignature); @@ -80489,8 +80637,9 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { - queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); } } } @@ -80505,7 +80654,7 @@ var ts; (function (ts) { function hasSameKeys(map1, map2) { // Has same size and every key is present in both maps - return map1 === map2 || map1 && map2 && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); } /** * Create the state so that we can iterate on changedFiles/affected files @@ -80533,7 +80682,7 @@ var ts; } // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; - var oldReferencedMap = useOldState && oldState.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; state.fileInfos.forEach(function (info, sourceFilePath) { var oldInfo; var newReferences; @@ -80577,7 +80726,7 @@ var ts; var affectedFiles = state.affectedFiles; if (affectedFiles) { var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; - var affectedFilesIndex = state.affectedFilesIndex; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 while (affectedFilesIndex < affectedFiles.length) { var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.path)) { @@ -80690,7 +80839,7 @@ var ts; // Return same program if underlying program doesnt change var oldState = oldProgram && oldProgram.getState(); if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { - newProgram = undefined; + newProgram = undefined; // TODO: GH#18217 oldState = undefined; return oldProgram; } @@ -80704,7 +80853,7 @@ var ts; var computeHash = host.createHash || ts.identity; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); // To ensure that we arent storing any references to old program or new program without state - newProgram = undefined; + newProgram = undefined; // TODO: GH#18217 oldProgram = undefined; oldState = undefined; var result = { @@ -80765,7 +80914,7 @@ var ts; if (!targetSourceFile) { // Emit and report any errors we ran into. var sourceMaps = []; - var emitSkipped = void 0; + var emitSkipped = false; var diagnostics = void 0; var emittedFiles = []; var affectedEmitResult = void 0; @@ -80885,7 +81034,7 @@ var ts; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; - var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. // The key in the map is source file's path. @@ -80906,7 +81055,7 @@ var ts; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); - var rootPath = rootDir && resolutionHost.toPath(rootDir); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames var typeRootsWatches = ts.createMap(); return { @@ -80964,7 +81113,7 @@ var ts; } // Invalidated if file has unresolved imports var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); - return value && !!value.length; + return !!value && !!value.length; } function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { @@ -80974,7 +81123,7 @@ var ts; } var collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = undefined; - return function (path) { return (collected && collected.has(path)) || + return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { @@ -81055,7 +81204,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -81126,7 +81275,7 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - return { dir: rootDir, dirPath: rootPath }; + return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } @@ -81190,7 +81339,7 @@ var ts; } } if (setAtRoot) { - setDirectoryWatcher(rootDir, rootPath); + setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 } } function setDirectoryWatcher(dir, dirPath, subDirectory) { @@ -81339,7 +81488,7 @@ var ts; // Resolution is invalidated if the resulting file name is same as the deleted file path function (resolution, getResolutionWithResolvedFileName) { var result = getResolutionWithResolvedFileName(resolution); - return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 }); } function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { @@ -81395,7 +81544,7 @@ var ts; return rootPath; } var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info @@ -81462,7 +81611,7 @@ var ts; getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, getNewLine: function () { return ts.sys.newLine; }, getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) - } : undefined; + } : undefined; // TODO: GH#18217 /** * Create a function that reports error by writing to the system and handles the formating of the diagnostic */ @@ -81479,7 +81628,7 @@ var ts; return function (diagnostic) { diagnostics[0] = diagnostic; system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); - diagnostics[0] = undefined; + diagnostics[0] = undefined; // TODO: GH#18217 }; } ts.createDiagnosticReporter = createDiagnosticReporter; @@ -81539,7 +81688,7 @@ var ts; var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); - host.onUnRecoverableConfigFileDiagnostic = undefined; + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; @@ -81669,9 +81818,9 @@ var ts; * Creates the watch compiler host from system for config file in watch mode */ function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { - reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); - var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; return host; @@ -81691,7 +81840,7 @@ var ts; (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -81718,7 +81867,7 @@ var ts; var configFileSpecs; var configFileParsingDiagnostics; var hasChangedConfigFileParsingErrors = false; - var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } @@ -81748,7 +81897,7 @@ var ts; var trace = host.trace && (function (s) { host.trace(s + newLine); }); var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : compilerOptions.diagnostis ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); @@ -81770,7 +81919,7 @@ var ts; readFile: readFile, trace: trace, directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), realpath: host.realpath && (function (s) { return host.realpath(s); }), getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), onReleaseOldSourceFile: onReleaseOldSourceFile, @@ -82059,12 +82208,12 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; - configFileSpecs = configFileParseResult.configFileSpecs; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } @@ -82443,6 +82592,13 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, + { + name: "strictAny", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_any_type + }, { name: "strictNullChecks", type: "boolean", @@ -82948,7 +83104,7 @@ var ts; case "string": return ts.map(values, function (v) { return v || ""; }); default: - return ts.filter(ts.map(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }), function (v) { return !!v; }); + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); } } ts.parseListTypeOption = parseListTypeOption; @@ -83371,6 +83527,7 @@ var ts; var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } + return false; } /** * Generate tsconfig configuration when running command line "--init" @@ -83423,7 +83580,7 @@ var ts; } else { if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 } else { // There is a typeMap associated with this command-line option so use it to map value back to its name @@ -83850,13 +84007,10 @@ var ts; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return undefined; + return false; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; + return typeof result === "boolean" && result; } function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; @@ -83885,7 +84039,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -84282,7 +84436,7 @@ var ts; if (optionEnumValue === value) { return optionStringValue; } - }); + }); // TODO: GH#18217 } } })(ts || (ts = {})); @@ -84710,7 +84864,7 @@ var ts; ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { var target = climbPastPropertyAccess(node); - return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -84773,6 +84927,8 @@ var ts; return true; case 177 /* LiteralType */: return node.parent.parent.kind === 175 /* IndexedAccessType */; + default: + return false; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -84946,7 +85102,7 @@ var ts; } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { + if (n === undefined || ts.nodeIsMissing(n)) { return false; } switch (n.kind) { @@ -84996,7 +85152,7 @@ var ts; // having at least a closing paren. return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); case 238 /* ModuleDeclaration */: - return n.body && isCompletedNode(n.body, sourceFile); + return !!n.body && isCompletedNode(n.body, sourceFile); case 216 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); @@ -85066,11 +85222,11 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last_2 = ts.lastOrUndefined(children); - if (last_2.kind === expectedLastToken) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { return true; } - else if (last_2.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -85130,6 +85286,7 @@ var ts; ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { + if (includeEndPosition === void 0) { includeEndPosition = false; } return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, includeEndPosition, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; @@ -85344,10 +85501,11 @@ var ts; var tokenKind = token.kind; var remainingMatchingTokens = 0; while (true) { - token = findPrecedingToken(token.getFullStart(), sourceFile); - if (!token) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { return undefined; } + token = preceding; if (token.kind === matchingTokenKind) { if (remainingMatchingTokens === 0) { return token; @@ -85360,21 +85518,24 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(token, sourceFile) { + function isPossiblyTypeArgumentPosition(tokenIn, sourceFile) { + var token = tokenIn; // This function determines if the node could be type argument position // Since during editing, when type argument list is not complete, // the tree could be of any shape depending on the tokens parsed before current node, // scanning of the previous identifier followed by "<" before current node would give us better result // Note that we also balance out the already provided type arguments, arrays, object literals while doing so var remainingLessThanTokens = 0; + var nTypeArguments = 0; while (token) { switch (token.kind) { case 27 /* LessThanToken */: // Found the beginning of the generic argument expression token = findPrecedingToken(token.getFullStart(), sourceFile); - var tokenIsIdentifier = token && ts.isIdentifier(token); - if (!remainingLessThanTokens || !tokenIsIdentifier) { - return tokenIsIdentifier; + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return { called: token, nTypeArguments: nTypeArguments }; } remainingLessThanTokens--; break; @@ -85392,24 +85553,26 @@ var ts; // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); if (!token) - return false; + return undefined; break; case 20 /* CloseParenToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); if (!token) - return false; + return undefined; break; case 22 /* CloseBracketToken */: // This can be object type, skip until we find the matching open brace token // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); if (!token) - return false; + return undefined; break; // Valid tokens in a type name. Skip. case 26 /* CommaToken */: + nTypeArguments++; + break; case 36 /* EqualsGreaterThanToken */: case 71 /* Identifier */: case 9 /* StringLiteral */: @@ -85429,11 +85592,11 @@ var ts; break; } // Invalid token in type - return false; + return undefined; } token = findPrecedingToken(token.getFullStart(), sourceFile); } - return false; + return undefined; } ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; /** @@ -85636,7 +85799,7 @@ var ts; } ts.repeatString = repeatString; function skipConstraint(type) { - return type.isTypeParameter() ? type.getConstraint() : type; + return type.isTypeParameter() ? type.getConstraint() : type; // TODO: GH#18217 } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { @@ -85662,16 +85825,16 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier) { + function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) - : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier, preferences.quotePreference === "single") : moduleSpecifier); } ts.makeImport = makeImport; function symbolNameNoDefault(symbol) { @@ -85897,18 +86060,21 @@ var ts; } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { - typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); @@ -85916,7 +86082,7 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return location.parent && + return !!location.parent && (location.parent.kind === 247 /* ImportSpecifier */ || location.parent.kind === 251 /* ExportSpecifier */) && location.parent.propertyName === location; } @@ -85944,7 +86110,7 @@ var ts; scriptKinds[_i - 2] = arguments[_i]; } var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); } ts.scriptKindIs = scriptKindIs; function getScriptKind(fileName, host) { @@ -86356,6 +86522,8 @@ var ts; case 9 /* text */: case 17 /* parameterName */: return ts.TokenClass.Identifier; + default: + return undefined; // TODO: GH#18217 Debug.assertNever(type); } } /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ @@ -86603,6 +86771,7 @@ var ts; case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; case 23 /* jsxText */: return "jsx text" /* jsxText */; case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type); } } function convertClassificationsToSpans(classifications) { @@ -86859,19 +87028,20 @@ var ts; } if (ts.isPunctuation(tokenKind)) { if (token) { + var parent = token.parent; if (tokenKind === 58 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 231 /* VariableDeclaration */ || - token.parent.kind === 151 /* PropertyDeclaration */ || - token.parent.kind === 148 /* Parameter */ || - token.parent.kind === 261 /* JsxAttribute */) { + if (parent.kind === 231 /* VariableDeclaration */ || + parent.kind === 151 /* PropertyDeclaration */ || + parent.kind === 148 /* Parameter */ || + parent.kind === 261 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 199 /* BinaryExpression */ || - token.parent.kind === 197 /* PrefixUnaryExpression */ || - token.parent.kind === 198 /* PostfixUnaryExpression */ || - token.parent.kind === 200 /* ConditionalExpression */) { + if (parent.kind === 199 /* BinaryExpression */ || + parent.kind === 197 /* PrefixUnaryExpression */ || + parent.kind === 198 /* PostfixUnaryExpression */ || + parent.kind === 200 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -86881,6 +87051,7 @@ var ts; return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { + // TODO: GH#18217 return token.parent.kind === 261 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 12 /* RegularExpressionLiteral */) { @@ -87006,7 +87177,7 @@ var ts; // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; - }); + }); // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } @@ -87210,8 +87381,8 @@ var ts; // after the last '/' that appears in the fragment because that's where the replacement span // starts if (fragmentDirectory !== undefined) { - var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); - return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); }); + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); } return nonRelativeModuleNames; } @@ -87321,7 +87492,7 @@ var ts; } return result; } - // Replace everything after the last directory seperator that appears + // Replace everything after the last directory separator that appears function getDirectoryFragmentTextSpan(text, textStart) { var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); var offset = index !== -1 ? index + 1 : 0; @@ -87366,7 +87537,7 @@ var ts; return ts.directoryProbablyExists(path, host); } catch ( /*ignore*/_a) { /*ignore*/ } - return undefined; + return false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; @@ -87414,7 +87585,7 @@ var ts; } var contextToken = ts.findPrecedingToken(position, sourceFile); if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) - return undefined; + return undefined; // TODO: GH#18217 if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined @@ -87424,7 +87595,7 @@ var ts; && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(program, log, sourceFile, position, preferences, /*detailsEntryId*/ undefined); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); if (!completionData) { return undefined; } @@ -87494,9 +87665,9 @@ var ts; }] }; } var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { + if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); + getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -87514,6 +87685,9 @@ var ts; } return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } function isMemberCompletionKind(kind) { switch (kind) { case 0 /* ObjectPropertyDeclaration */: @@ -87632,7 +87806,7 @@ var ts; continue; } // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 uniques.set(name, true); } entries.push(entry); @@ -87728,7 +87902,7 @@ var ts; case 186 /* CallExpression */: case 187 /* NewExpression */: if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); // f("/*completion position*/") @@ -87783,7 +87957,8 @@ var ts; : ts.emptyArray; } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { - var completionData = getCompletionData(program, log, sourceFile, position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); if (!completionData) { return { type: "none" }; } @@ -87797,7 +87972,7 @@ var ts; // completion entry. return ts.firstDefined(symbols, function (symbol) { var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - var info = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, origin, completionKind); + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; @@ -87819,7 +87994,7 @@ var ts; var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); - return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); @@ -87840,7 +88015,7 @@ var ts; case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; - return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. @@ -87905,12 +88080,15 @@ var ts; CompletionKind[CompletionKind["None"] = 5] = "None"; })(CompletionKind || (CompletionKind = {})); function getRecommendedCompletion(currentToken, position, sourceFile, checker) { - var ty = getContextualType(currentToken, position, sourceFile, checker); - var symbol = ty && ty.symbol; - // Don't include make a recommended completion for an abstract class - return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) - ? getFirstSymbolInChain(symbol, currentToken, checker) - : undefined; + var contextualType = getContextualType(currentToken, position, sourceFile, checker); + // For a union, return the first one with a recommended completion. + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, currentToken, checker) + : undefined; + }); } function getContextualType(currentToken, position, sourceFile, checker) { var parent = currentToken.parent; @@ -87920,7 +88098,7 @@ var ts; case 58 /* EqualsToken */: switch (parent.kind) { case 231 /* VariableDeclaration */: - return checker.getContextualType(parent.initializer); + return checker.getContextualType(parent.initializer); // TODO: GH#18217 case 199 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); case 261 /* JsxAttribute */: @@ -87935,7 +88113,7 @@ var ts; case 17 /* OpenBraceToken */: return ts.isJsxExpression(parent) && parent.parent.kind !== 254 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: - var argInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(currentToken, position, sourceFile); + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(currentToken, position, sourceFile); return argInfo // At `,`, treat this as the next argument after the comma. ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (currentToken.kind === 26 /* CommaToken */ ? 1 : 0)) @@ -87974,7 +88152,7 @@ var ts; function isModuleSymbol(symbol) { return symbol.declarations.some(function (d) { return d.kind === 273 /* SourceFile */; }); } - function getCompletionData(program, log, sourceFile, position, preferences, detailsEntryId) { + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 @@ -88046,7 +88224,7 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217 log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file @@ -88055,7 +88233,7 @@ var ts; // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { var start_4 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } // Find the node where completion is requested on. @@ -88086,6 +88264,7 @@ var ts; node = parent.left; break; case 178 /* ImportType */: + case 209 /* MetaProperty */: node = parent; break; default: @@ -88195,6 +88374,8 @@ var ts; case 294 /* JSDocTypeTag */: case 296 /* JSDocTypedefTag */: return true; + default: + return false; } } function getTypeScriptMemberSymbols() { @@ -88232,13 +88413,18 @@ var ts; } } } + if (ts.isMetaProperty(node) && (node.keywordToken === 94 /* NewKeyword */ || node.keywordToken === 91 /* ImportKeyword */)) { + var completion = (node.keywordToken === 94 /* NewKeyword */) ? "target" : "meta"; + symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); + return; + } if (!isTypeLocation) { addTypeProperties(typeChecker.getTypeAtLocation(node)); } } function addTypeProperties(type) { isNewIdentifierLocation = hasIndexSignature(type); - if (ts.isSourceFileJavaScript(sourceFile)) { + if (isUncheckedFile) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that // each individual type has. This is because we're going to add all identifiers @@ -88377,7 +88563,7 @@ var ts; if (ts.programContainsEs6Modules(program)) return true; // For JS, stay on the safe side. - if (ts.isSourceFileJavaScript(sourceFile)) + if (isUncheckedFile) return false; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); @@ -88457,6 +88643,7 @@ var ts; // symbol can be referenced at locations where type is allowed return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); } + return false; } function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { var tokenTextLowerCase = tokenText.toLowerCase(); @@ -88539,7 +88726,7 @@ var ts; return true; } if (contextToken.parent.kind === 257 /* JsxClosingElement */ || contextToken.parent.kind === 255 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 254 /* JsxElement */; + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 254 /* JsxElement */; } } return false; @@ -88696,7 +88883,7 @@ var ts; // cursor is in an import clause // try to show exported member for imported module var moduleSpecifier = (namedImportsOrExports.kind === 246 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; completionKind = 3 /* MemberLike */; @@ -88723,7 +88910,7 @@ var ts; if (!ts.isClassLike(decl)) return 1 /* Success */; var classElement = contextToken.parent; - var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); + var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */; // If this is context token is not something we are editing now, consider if this would lead to be modifier if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { @@ -88739,7 +88926,7 @@ var ts; if (!(classElementModifierFlags & 8 /* Private */)) { // List of property symbols of base type that are not private and already implemented var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { - var type = typeChecker.getTypeAtLocation(baseTypeNode); + var type = typeChecker.getTypeAtLocation(baseTypeNode); // TODO: GH#18217 return typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); }); symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); @@ -88774,13 +88961,14 @@ var ts; */ function tryGetConstructorLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 19 /* OpenParenToken */: case 26 /* CommaToken */: - return ts.isConstructorDeclaration(contextToken.parent) && contextToken.parent; + return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined; default: if (isConstructorParameterCompletion(contextToken)) { - return contextToken.parent.parent; + return parent.parent; } } } @@ -88797,6 +88985,7 @@ var ts; return true; } prev_1 = node; + return false; }); return container && container; } @@ -88862,7 +89051,8 @@ var ts; * @returns true if we are certain that the currently edited location must define a new location; false otherwise. */ function isSolelyIdentifierDefinitionLocation(contextToken) { - var containingNodeKind = contextToken.parent.kind; + var parent = contextToken.parent; + var containingNodeKind = parent.kind; switch (contextToken.kind) { case 26 /* CommaToken */: return containingNodeKind === 231 /* VariableDeclaration */ || @@ -88875,9 +89065,9 @@ var ts; containingNodeKind === 236 /* TypeAliasDeclaration */ || // type Map, K, | // class A= contextToken.pos); + (ts.isClassLike(parent) && + !!parent.typeParameters && + parent.typeParameters.end >= contextToken.pos); case 23 /* DotToken */: return containingNodeKind === 180 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: @@ -88896,15 +89086,14 @@ var ts; containingNodeKind === 236 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 151 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); + return containingNodeKind === 151 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 148 /* Parameter */ || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 180 /* ArrayBindingPattern */); // var [...z| + (!!parent.parent && parent.parent.kind === 180 /* ArrayBindingPattern */); // var [...z| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 148 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); + return containingNodeKind === 148 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 118 /* AsKeyword */: return containingNodeKind === 247 /* ImportSpecifier */ || containingNodeKind === 251 /* ExportSpecifier */ || @@ -89005,7 +89194,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 181 /* BindingElement */ && m.propertyName) { + if (ts.isBindingElement(m) && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 71 /* Identifier */) { existingName = m.propertyName.escapedText; @@ -89018,7 +89207,7 @@ var ts; var name = ts.getNameOfDeclaration(m); existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } - existingMemberNames.set(existingName, true); + existingMemberNames.set(existingName, true); // TODO: GH#18217 } return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); } @@ -89255,7 +89444,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) + return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -89337,7 +89526,7 @@ var ts; if (!sourceFilesSet.has(fileName)) { ts.Debug.assert(program.redirectTargetsSet.has(fileName)); var redirectTarget_1 = program.getSourceFile(fileName); - var redirect = ts.find(sourceFilesToSearch, function (f) { return f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; ts.Debug.assert(sourceFilesSet.has(fileName)); } @@ -89410,7 +89599,7 @@ var ts; } else if (ts.isTryStatement(node)) { // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. - return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), aggregateOwnedThrowStatements(node.finallyBlock)); + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); } // Do not cross function boundaries. return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); @@ -89451,7 +89640,7 @@ var ts; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; + return !!actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { @@ -89502,9 +89691,8 @@ var ts; } case 154 /* Constructor */: case 153 /* MethodDeclaration */: - case 233 /* FunctionDeclaration */: { + case 233 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - } case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: var nodes = container.members; @@ -89720,6 +89908,11 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. @@ -89733,7 +89926,7 @@ var ts; if (!bucket && createIfMissing) { buckets.set(key, bucket = ts.createMap()); } - return bucket; + return bucket; // TODO: GH#18217 } function reportStats() { var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { @@ -89742,8 +89935,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -89774,13 +89966,26 @@ var ts; var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } @@ -89789,7 +89994,10 @@ var ts; // the script snapshot. If so, update it appropriately. Otherwise, we can just // return it as is. if (entry.sourceFile.version !== version) { - entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } // If we're acquiring, then this is the first time this LS is asking for this document. // Increase our ref count so we know there's another LS using the document. If we're @@ -89800,6 +90008,7 @@ var ts; entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -89817,6 +90026,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -89824,11 +90040,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -89965,7 +90182,7 @@ var ts; ts.Debug.assert(!isAvailableThroughGlobal); var isNew = markSeenIndirectUser(sourceFileLike); if (isNew) { - indirectUserDeclarations.push(sourceFileLike); + indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217 } return isNew; } @@ -90046,7 +90263,7 @@ var ts; return; } if (exportKind === 0 /* Named */) { - searchForNamedImport(namedBindings); + searchForNamedImport(namedBindings); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) } else { // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals @@ -90110,7 +90327,7 @@ var ts; /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); - return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { if (!ts.isExportDeclaration(statement)) return; var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; @@ -90216,12 +90433,13 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; + var grandParent = parent.parent; if (symbol.exportSymbol) { if (parent.kind === 184 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) - ? getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ false) + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) : undefined; } else { @@ -90248,15 +90466,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(parent.parent)) { - return getExportAssignmentExport(parent.parent); + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(parent.parent)) { - return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -90331,6 +90549,9 @@ var ts; else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } // If a reference is a class expression, the exported node would be its parent. @@ -90626,6 +90847,7 @@ var ts; } var moduleReferences = ts.emptyArray; var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; if (moduleSourceFile) { var exportEquals = symbol.exports.get("export=" /* ExportEquals */); // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. @@ -90634,13 +90856,13 @@ var ts; return moduleReferences; // Continue to get references to 'export ='. symbol = ts.skipAlias(exportEquals, checker); - node = undefined; + referencedNode = undefined; } - return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; function isModuleSymbol(symbol) { - return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile); + return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; } function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); @@ -90718,7 +90940,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -90826,7 +91048,7 @@ var ts; State.prototype.getImportSearches = function (exportSymbol, exportInfo) { if (!this.importTracker) this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); - return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); }; /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { @@ -90837,7 +91059,7 @@ var ts; // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** @@ -90938,8 +91160,9 @@ var ts; } } function getPropertySymbolOfDestructuringAssignment(location, checker) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - checker.getPropertySymbolOfDestructuringAssignment(location); + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; } function getObjectBindingElementWithoutPropertyName(symbol) { var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */); @@ -90998,8 +91221,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -91018,7 +91241,7 @@ var ts; // declare module "a" { export type T = number; } // declare module "b" { import { T } from "a"; export const x: T; } // 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; + return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 } /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ function isSymbolReferencedInFile(definition, checker, sourceFile) { @@ -91210,7 +91433,8 @@ var ts; if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - ts.Debug.assert(!!exportInfo); + if (!exportInfo) + return ts.Debug.fail(); searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. @@ -91346,8 +91570,7 @@ var ts; } /** Find references to `super` in the constructor of an extending class. */ function findSuperConstructorAccesses(cls, addNode) { - var symbol = cls.symbol; - var ctr = symbol.members.get("__constructor" /* Constructor */); + var ctr = cls.symbol.members.get("__constructor" /* Constructor */); if (!ctr) { return; } @@ -91690,7 +91913,7 @@ var ts; var name = ts.getNameFromPropertyName(node.name); var symbol = contextualType && name && contextualType.getProperty(name); return symbol ? [symbol] : - contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; + contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; // TODO: GH#18217 } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations @@ -91712,8 +91935,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -91774,6 +91997,72 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { + var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); + for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; + var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); + if (newPath !== undefined) { + var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); + changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); + } + } + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); + if (oldFile) { + changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + } + } + function isRef(toUpdate) { + return "fileName" in toUpdate; + } + function getImportsToUpdate(program, oldFilePath, host) { + var result = []; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var ref = _c[_b]; + if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { + result.push({ sourceFile: sourceFile, toUpdate: ref }); + } + } + for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { + var importStringLiteral = _e[_d]; + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); + // We may or may not have picked up on the file being renamed, so maybe successfully resolved to oldFilePath, or maybe that's in failedLookupLocations + if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { + result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); + } + } + } + return result; + } + function getPathUpdater(oldFilePath, newFilePath, host) { + // Get the relative path from old to new location, and append it on to the end of imports and normalize. + var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); + return function (oldPath) { + if (!ts.pathIsRelative(oldPath)) + return; + return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); + }; + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -91786,10 +92075,11 @@ var ts; if (node === sourceFile) { return undefined; } + var parent = node.parent; // Labels if (ts.isJumpStatementTarget(node)) { var label = ts.getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } var typeChecker = program.getTypeChecker(); var symbol = getSymbol(node, typeChecker); @@ -91805,7 +92095,7 @@ var ts; // If this is the original constructor definition, parent is the class. return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) || // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias - symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); }) + symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); }) ? [sigInfo] : [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node)); } @@ -91829,9 +92119,9 @@ var ts; // pr/*destination*/op1: number // } // bar(({pr/*goto*/op1})=>{}); - if (ts.isPropertyName(node) && ts.isBindingElement(node.parent) && ts.isObjectBindingPattern(node.parent.parent) && - (node === (node.parent.propertyName || node.parent.name))) { - var type = typeChecker.getTypeAtLocation(node.parent.parent); + if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var type = typeChecker.getTypeAtLocation(parent.parent); if (type) { var propSymbols = ts.getPropertySymbolsFromType(type, node); if (propSymbols) { @@ -91866,7 +92156,7 @@ var ts; var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - var file_17 = reference && program.getSourceFile(reference.resolvedFileName); + var file_17 = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 return file_17 && { fileName: typeReferenceDirective.fileName, file: file_17 }; } return undefined; @@ -92009,14 +92299,14 @@ var ts; kind: "script" /* scriptElement */, name: name, containerName: undefined, - containerKind: undefined + containerKind: undefined, }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ function getAncestorCallLikeExpression(node) { var target = climbPastManyPropertyAccesses(node); var callLike = target.parent; - return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; } function climbPastManyPropertyAccesses(node) { return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; @@ -92220,7 +92510,7 @@ var ts; if (!ts.isIdentifier(param.name)) return undefined; var name = param.name.text; - if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217 || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { return undefined; } @@ -92378,7 +92668,7 @@ var ts; return rightHandSide.parameters; case 204 /* ClassExpression */: { var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); - return ctr && ctr.parameters; + return ctr ? ctr.parameters : ts.emptyArray; } } return ts.emptyArray; @@ -92589,7 +92879,7 @@ var ts; return result; function addInferredTyping(typingName) { if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); + inferredTypings.set(typingName, undefined); // TODO: GH#18217 } } function addInferredTypings(typingNames, message) { @@ -92740,7 +93030,7 @@ var ts; case 0 /* Ok */: return ts.Debug.fail(); // Shouldn't have called this. default: - ts.Debug.assertNever(result); + throw ts.Debug.assertNever(result); } } JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; @@ -92784,12 +93074,12 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { - var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); // TODO: GH#18217 if (fullMatch) { rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); } @@ -92854,12 +93144,12 @@ var ts; return undefined; } // Now, walk up our containers, adding all their names to the container array. - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { return undefined; } - declaration = ts.getContainerNode(declaration); + container = ts.getContainerNode(container); } return containers; } @@ -92882,7 +93172,7 @@ var ts; textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ // TODO: GH#18217 Just use `container ? ...` }; } })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); @@ -93216,6 +93506,7 @@ var ts; // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { + // TODO: GH#18217 return a.body.kind === b.body.kind && (a.body.kind !== 238 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ @@ -93237,7 +93528,7 @@ var ts; children.sort(compareChildren); } function compareChildren(child1, child2) { - return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217 || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); } /** @@ -93251,7 +93542,7 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName) { - return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { case 191 /* FunctionExpression */: @@ -93359,7 +93650,7 @@ var ts; } } function hasSomeImportantChild(item) { - return ts.forEach(item.children, function (child) { + return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); return childKind !== 231 /* VariableDeclaration */ && childKind !== 181 /* BindingElement */; }); @@ -93428,7 +93719,7 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 238 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 238 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217 } function isComputedProperty(member) { return !member.name || member.name.kind === 146 /* ComputedPropertyName */; @@ -93501,7 +93792,7 @@ var ts; organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; - var ambientModuleBody = getModuleBlock(ambientModule); + var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); @@ -93549,12 +93840,12 @@ var ts; OrganizeImports.organizeImports = organizeImports; function getModuleBlock(moduleDecl) { var body = moduleDecl.body; - return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -93592,8 +93883,8 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - // The JSX factory symbol is always used. - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { @@ -93619,16 +93910,16 @@ var ts; if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { // Add the namespace import to the existing default ImportDeclaration. var defaultImport = defaultImports[0]; - coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217 return coalescedImports; } var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); - }); + }); // TODO: GH#18217 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, /*name*/ undefined, namespaceImport.importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217 } if (defaultImports.length === 0 && namedImports.length === 0) { return coalescedImports; @@ -93641,10 +93932,10 @@ var ts; 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.importClause.name)); + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] @@ -93655,7 +93946,7 @@ var ts; : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) - : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); return coalescedImports; /* @@ -93749,7 +94040,8 @@ var ts; } OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier); } function sortSpecifiers(specifiers) { return ts.stableSort(specifiers, function (s1, s2) { @@ -93773,73 +94065,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); - return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) { - var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate; - var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text); - if (newPath !== undefined) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } - }); - } - ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { - var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); - } - } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var checker = program.getTypeChecker(); - var result = []; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (!program.getSourceFileFromReference(sourceFile, ref) && ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - // If it resolved to something already, ignore. - if (checker.getSymbolAtLocation(importStringLiteral)) - continue; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } - } - return result; - } - function getPathUpdater(oldFilePath, newFilePath, host) { - // Get the relative path from old to new location, and append it on to the end of imports and normalize. - var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; - } - function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); - } -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { @@ -94075,7 +94300,7 @@ var ts; // First, check that the last part of the dot separated pattern matches the name of the // candidate. If not, then there's no point in proceeding and doing the more // expensive work. - var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments), stringToWordSpans); + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); if (!candidateMatch) { return undefined; } @@ -94808,7 +95033,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, 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 @@ -94827,7 +95052,7 @@ var ts; } } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -94899,6 +95124,7 @@ var ts; }; } function getRenameInfoError(diagnostic) { + // TODO: GH#18217 return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), @@ -94944,7 +95170,12 @@ var ts; ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); + })(ArgumentListKind || (ArgumentListKind = {})); + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + })(InvocationKind || (InvocationKind = {})); function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { var typeChecker = program.getTypeChecker(); // Decide whether to show signature help @@ -94958,11 +95189,9 @@ var ts; return undefined; cancellationToken.throwIfCancellationRequested(); // Semantic filtering of signature help - var call = argumentInfo.invocation; - var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker); cancellationToken.throwIfCancellationRequested(); - if (!candidates.length) { + if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. if (ts.isSourceFileJavaScript(sourceFile)) { @@ -94970,54 +95199,76 @@ var ts; } return undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { - if (argumentInfo.invocation.kind !== 186 /* CallExpression */) { - return undefined; + function getCandidateInfo(argumentInfo, checker) { + var invocation = argumentInfo.invocation; + if (invocation.kind === 0 /* Call */) { + var candidates = []; + var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; } + else { + var type = checker.getTypeAtLocation(invocation.called); // TODO: GH#18217 + var signatures = ts.isNewExpression(invocation.called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + var candidates = signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= argumentInfo.argumentCount; }); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + } + function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { // See if we can find some symbol with the call expression name that has call signatures. - var callExpression = argumentInfo.invocation; - var expression = callExpression.expression; + var expression = getExpressionFromInvocation(argumentInfo.invocation); var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + var _loop_16 = function (sourceFile) { var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_16 = function (declaration) { + var _loop_17 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); if (type) { var callSignatures_1 = type.getCallSignatures(); if (callSignatures_1 && callSignatures_1.length) { - return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, typeChecker); }) }; + return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; } } } }; - for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { - var declaration = declarations_12[_b]; - var state_5 = _loop_16(declaration); - if (typeof state_5 === "object") - return state_5.value; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var state_6 = _loop_17(declaration); + if (typeof state_6 === "object") + return state_6; } } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var state_5 = _loop_16(sourceFile); + if (typeof state_5 === "object") + return state_5.value; } } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.kind === 0 /* TypeArguments */ || info.invocation.kind === 1 /* TypeArgs */ ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; /** * Returns relevant information for the argument list and the current argument if we are * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (ts.isCallOrNewExpression(node.parent)) { - var invocation = node.parent; + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; var list = void 0; var argumentIndex = void 0; // There are 3 cases to handle: @@ -95037,7 +95288,7 @@ var ts; if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); + list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); ts.Debug.assert(list !== undefined); argumentIndex = 0; } @@ -95053,60 +95304,66 @@ var ts; return undefined; argumentIndex = getArgumentIndex(list, node); } - var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; + var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; var argumentCount = getArgumentCount(list); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + return { kind: kind, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 188 /* TaggedTemplateExpression */) { + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { - return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); + return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 188 /* TaggedTemplateExpression */) { - var templateExpression = node.parent; + else if (ts.isTemplateHead(node) && parent.parent.kind === 188 /* TaggedTemplateExpression */) { + var templateExpression = parent; var tagExpression = templateExpression.parent; ts.Debug.assert(templateExpression.kind === 201 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 210 /* TemplateSpan */ && node.parent.parent.parent.kind === 188 /* TaggedTemplateExpression */) { - var templateSpan = node.parent; - var templateExpression = templateSpan.parent; - var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 201 /* TemplateExpression */); + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; // If we're just after a template tail, don't show signature help. if (node.kind === 16 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } - var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position); return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent && ts.isJsxOpeningLikeElement(node.parent)) { + else if (ts.isJsxOpeningLikeElement(parent)) { // Provide a signature help for JSX opening element or JSX self-closing element. // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") // i.e // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } // 0 && ts.lastOrUndefined(listChildren).kind === 26 /* CommaToken */) { + if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -95183,7 +95440,7 @@ var ts; } return { kind: 2 /* TaggedTemplateArguments */, - invocation: tagExpression, + invocation: { kind: 0 /* Call */, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, argumentCount: argumentCount @@ -95215,7 +95472,7 @@ var ts; // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === 201 /* TemplateExpression */) { - var lastSpan = ts.lastOrUndefined(template.templateSpans); + var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } @@ -95223,39 +95480,40 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 273 /* SourceFile */; n = n.parent) { - if (ts.isFunctionBlock(n)) { - return undefined; - } + var _loop_18 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. - if (n.pos < n.parent.pos || n.end > n.parent.end) { - ts.Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); - } + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); if (argumentInfo) { - return argumentInfo; + return { value: argumentInfo }; } - // TODO: Handle generic call with incomplete syntax + }; + for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { + var state_7 = _loop_18(n); + if (typeof state_7 === "object") + return state_7.value; } return undefined; } - SignatureHelp.getContainingArgumentInfo = getContainingArgumentInfo; function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { var children = parent.getChildren(sourceFile); var indexOfOpenerToken = children.indexOf(openerToken); ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var callTarget = ts.getInvokedExpression(invocation); - var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); + var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.called; + var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); var printer = ts.createPrinter({ removeComments: true }); - var items = ts.map(candidates, function (candidateSignature) { + var items = candidates.map(function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; var suffixDisplayParts = []; @@ -95270,9 +95528,9 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); }); ts.addRange(suffixDisplayParts, parameterParts); } @@ -95280,8 +95538,8 @@ var ts; isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); - printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); } }); ts.addRange(prefixDisplayParts, typeParameterParts); @@ -95294,10 +95552,10 @@ var ts; writer.writeSpace(" "); var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); if (predicate) { - typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + typeChecker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); } else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); } }); ts.addRange(suffixDisplayParts, returnTypeParts); @@ -95319,8 +95577,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: parameter.name, @@ -95331,8 +95589,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, @@ -95362,8 +95620,7 @@ var ts; case 233 /* FunctionDeclaration */: case 191 /* FunctionExpression */: if (isJsFile) { - var symbol = node.symbol; - if (symbol.members && (symbol.members.size > 0)) { + if (node.symbol.members && (node.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)); } } @@ -95402,6 +95659,7 @@ var ts; } } } + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; }); } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; @@ -95412,7 +95670,7 @@ var ts; case 213 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); + }); // TODO: GH#18217 case 215 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) @@ -95432,7 +95690,7 @@ var ts; switch (node.kind) { case 243 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings.kind === 245 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 245 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; case 242 /* ImportEqualsDeclaration */: @@ -95576,7 +95834,7 @@ var ts; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - var hasAddedSymbolInfo; + var hasAddedSymbolInfo = false; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; var printer; @@ -95610,7 +95868,7 @@ var ts; } if (callExpressionLike) { var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 var useConstructSignatures = callExpressionLike.kind === 187 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { @@ -95676,7 +95934,7 @@ var ts; if (locationIsSymbolDeclaration) { var allSignatures = functionDeclaration_1.kind === 154 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; @@ -95764,12 +96022,13 @@ var ts; else { // Method/function type parameter var decl = ts.getDeclarationOfKind(symbol, 147 /* TypeParameter */); - ts.Debug.assert(decl !== undefined); + if (decl === undefined) + return ts.Debug.fail(); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); - var signature = typeChecker.getSignatureFromDeclaration(declaration); + var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 if (declaration.kind === 158 /* ConstructSignature */) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); @@ -96009,6 +96268,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0 /* None */; } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); @@ -96094,7 +96354,7 @@ var ts; options.noResolve = true; // if jsx is specified then treat file as .tsx var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); - var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217 if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } @@ -96135,7 +96395,8 @@ var ts; } // Emit program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } ts.transpileModule = transpileModule; @@ -96158,7 +96419,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_19 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -96177,7 +96438,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_19(opt); } return options; } @@ -96314,7 +96575,7 @@ var ts; lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */; } else { scanner.scan(); @@ -97068,7 +97329,7 @@ var ts; } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - context.contextNode.decorators && + !!context.contextNode.decorators && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -97373,7 +97634,7 @@ var ts; return ts.rangeContainsRange(parent.members, node); case 238 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 239 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + return !!body && body.kind === 239 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); case 273 /* SourceFile */: case 212 /* Block */: case 239 /* ModuleBlock */: @@ -97407,7 +97668,7 @@ var ts; } // pick only errors that fall in range var sorted = errors - .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217 .sort(function (e1, e2) { return e1.start - e2.start; }); if (!sorted.length) { return rangeHasNoErrors; @@ -97535,7 +97796,7 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); + processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217 trimTrailingWhitespacesForRemainingRange(); } } @@ -97896,6 +98157,7 @@ var ts; } } } + // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAction = 0 /* None */; @@ -98368,7 +98630,7 @@ var ts; // handle cases when codefix is about to be inserted before the close brace ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 : lineAtPosition !== currentStart.line ? options.indentSize : 0; - return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 } // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); @@ -98377,7 +98639,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; + return actualIndentation + options.indentSize; // TODO: GH#18217 } previous = current; current = current.parent; @@ -98674,8 +98936,9 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { case 215 /* ExpressionStatement */: case 234 /* ClassDeclaration */: case 204 /* ClassExpression */: @@ -98697,7 +98960,6 @@ var ts; case 186 /* CallExpression */: case 187 /* NewExpression */: case 213 /* VariableStatement */: - case 231 /* VariableDeclaration */: case 248 /* ExportAssignment */: case 224 /* ReturnStatement */: case 200 /* ConditionalExpression */: @@ -98720,22 +98982,14 @@ var ts; case 246 /* NamedImports */: case 251 /* ExportSpecifier */: case 247 /* ImportSpecifier */: - case 269 /* PropertyAssignment */: case 151 /* PropertyDeclaration */: return true; - } - return false; - } - function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { - var childKind = child ? child.kind : 0 /* Unknown */; - switch (parent.kind) { case 231 /* VariableDeclaration */: case 269 /* PropertyAssignment */: - case 183 /* ObjectLiteralExpression */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183 /* ObjectLiteralExpression */) { + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 183 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } - break; + return true; case 217 /* DoStatement */: case 218 /* WhileStatement */: case 220 /* ForInStatement */: @@ -98759,6 +99013,12 @@ var ts; return childKind !== 257 /* JsxClosingElement */; case 258 /* JsxFragment */: return childKind !== 260 /* JsxClosingFragment */; + case 169 /* IntersectionType */: + case 168 /* UnionType */: + if (childKind === 165 /* TypeLiteral */) { + return false; + } + // falls through } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -98788,7 +99048,7 @@ var ts; */ function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; @@ -98905,7 +99165,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 183 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 183 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -99358,7 +99618,7 @@ var ts; var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); } return changes; }; @@ -99383,14 +99643,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_20 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_18(i); + _loop_20(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -99399,8 +99659,12 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter) { - var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; @@ -99414,7 +99678,7 @@ var ts; 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(change.options.joiner || newLineCharacter) + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217 : format(change.node); // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); @@ -99457,7 +99721,7 @@ var ts; return ts.skipTrivia(s, 0) === s.length; } function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217 // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); @@ -99877,7 +100141,7 @@ var ts; case 161 /* TypeReference */: return transformJSDocTypeReference(node); default: - var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 ts.setEmitFlags(visited, 1 /* SingleLine */); return visited; } @@ -99896,7 +100160,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 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); @@ -99981,7 +100245,7 @@ var ts; precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { - copyComments(precedingNode, newClassDeclaration, sourceFile); + copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 deleteNode(precedingNode); } else { @@ -100153,13 +100417,13 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); } } }); @@ -100167,7 +100431,7 @@ var ts; return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -100177,7 +100441,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, preferences)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -100188,14 +100452,14 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { 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); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -100230,10 +100494,10 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { switch (statement.kind) { case 213 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); return false; case 215 /* ExpressionStatement */: { var expression = statement.expression; @@ -100241,7 +100505,7 @@ var ts; case 186 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0])); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], preferences)); } return false; } @@ -100256,7 +100520,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -100269,11 +100533,11 @@ var ts; } else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); } } // Move it out to its own variable statement. (This will not be used if `!foundImport`) @@ -100285,22 +100549,22 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { switch (name.kind) { case 179 /* ObjectBindingPattern */: case 180 /* 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), + makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), 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)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } function convertAssignment(sourceFile, checker, assignment, changes, exports) { @@ -100432,7 +100696,7 @@ var ts; } function exportConst() { // `exports.x = 0;` --> `export const x = 0;` - return makeConst(modifiers, ts.createIdentifier(name), exported); + return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217 } } /** @@ -100440,16 +100704,16 @@ var ts; * 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) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { switch (name.kind) { case 179 /* 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); - }); + }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) if (importSpecifiers) { - return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, preferences)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -100460,21 +100724,21 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, preferences), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); default: - ts.Debug.assertNever(name); + return 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) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { 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(); @@ -100509,7 +100773,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -100549,10 +100813,10 @@ var ts; 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) { + function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, preferences) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -100677,7 +100941,9 @@ var ts; ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, ], - getCodeActions: getImportCodeActions, + getCodeActions: function (context) { return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(context) + : getActionsForNonUMDImport(context); }, // TODO: GH#20315 fixIds: [], getAllCodeActions: ts.notImplemented, @@ -100696,7 +100962,6 @@ var ts; program: program, checker: checker, compilerOptions: program.getCompilerOptions(), - cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(context.host)), symbolName: symbolName, symbolToken: symbolToken, @@ -100742,9 +101007,17 @@ var ts; return result; } function getCodeActionsForImport_separateExistingAndNew(exportInfos, context, useExisting, addNew) { - var existingImports = ts.flatMap(exportInfos, function (info) { - return getImportDeclarations(info, context.checker, context.sourceFile, context.cachedImportDeclarations); - }); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, context.checker, context.sourceFile); }); + ts.append(useExisting, tryUseExistingNamespaceImport(existingImports, context, context.symbolToken, context.checker)); + var addToExisting = tryAddToExistingImport(existingImports, context); + if (addToExisting) { + useExisting.push(addToExisting); + } + else { // Don't bother providing an action to add a new import if we can add to an existing one. + getCodeActionsForAddImport(exportInfos, context, existingImports, addNew); + } + } + function tryUseExistingNamespaceImport(existingImports, context, symbolToken, checker) { // It is possible that multiple import statements with the same specifier exist in the file. // e.g. // @@ -100757,19 +101030,28 @@ var ts; // 1. change "member3" to "ns.member3" // 2. add "member3" to the second import statement's import list // and it is up to the user to decide which one fits best. - if (context.symbolToken && ts.isIdentifier(context.symbolToken)) { - for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) { - var declaration = existingImports_1[_i].declaration; - var namespace_2 = getNamespaceImportName(declaration); - if (namespace_2) { - var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2)); - if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken)); - } + return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = namespace && checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { + return getCodeActionForUseExistingNamespaceImport(namespace.text, context, symbolToken); } } - } - getCodeActionsForAddImport(exportInfos, context, existingImports, useExisting, addNew); + }); + } + function tryAddToExistingImport(existingImports, context) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind === 243 /* ImportDeclaration */ && declaration.importClause) { + var changes = tryUpdateExistingImport(context, declaration.importClause, importKind); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [context.symbolName, moduleSpecifierWithoutQuotes], changes); + } + } + }); } function getNamespaceImportName(declaration) { if (declaration.kind === 243 /* ImportDeclaration */) { @@ -100780,21 +101062,14 @@ var ts; return declaration.name; } } - // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? - function getImportDeclarations(_a, checker, _b, cachedImportDeclarations) { + function getExistingImportDeclarations(_a, checker, _b) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; var imports = _b.imports; - if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } - var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (moduleSpecifier) { - var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 243 /* ImportDeclaration */ || i.kind === 242 /* ImportEqualsDeclaration */) - && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; - }); - } - return cached; + return ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 243 /* ImportDeclaration */ || i.kind === 242 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); } function getCodeActionForNewImport(context, _a) { var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; @@ -100819,7 +101094,7 @@ var ts; }); // if this file doesn't have any import statements, insert an import statement and then insert a new line // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. + // are there are already a new line separating code and import statements. return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } function shouldUseSingleQuote(sourceFile, preferences) { @@ -100853,21 +101128,7 @@ var ts; // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) { - var fromExistingImport = ts.firstDefined(existingImports, function (_a) { - var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 243 /* ImportDeclaration */ && declaration.importClause) { - var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined, importKind); - if (changes) { - var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); - return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes); - } - } - }); - if (fromExistingImport) { - useExisting.push(fromExistingImport); - return; - } + function getCodeActionsForAddImport(exportInfos, ctx, existingImports, addNew) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); var newImportInfos = existingDeclaration ? [existingDeclaration] @@ -100889,7 +101150,7 @@ var ts; function tryUpdateExistingImport(context, importClause, importKind) { var symbolName = context.symbolName, sourceFile = context.sourceFile; var name = importClause.name; - var namedBindings = (importClause.kind !== 242 /* ImportEqualsDeclaration */ && importClause).namedBindings; + var namedBindings = (importClause.kind !== 242 /* ImportEqualsDeclaration */ && importClause).namedBindings; // TODO: GH#18217 switch (importKind) { case 1 /* Default */: return name ? undefined : ChangeTracker.with(context, function (t) { @@ -100935,11 +101196,6 @@ var ts; }); return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes); } - function getImportCodeActions(context) { - return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ? getActionsForUMDImport(context) - : getActionsForNonUMDImport(context); - } function getActionsForUMDImport(context) { var token = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); @@ -101001,7 +101257,14 @@ var ts; return undefined; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default"); - var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + var addToExistingDeclaration = []; + var addNewDeclaration = []; + getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).forEach(function (exportInfos) { + getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration); + }); + return addToExistingDeclaration.concat(addNewDeclaration); + } + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); @@ -101026,7 +101289,7 @@ var ts; addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); } function getEscapedNameForExportDefault(symbol) { - return ts.firstDefined(symbol.declarations, function (declaration) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { if (ts.isExportAssignment(declaration)) { if (ts.isIdentifier(declaration.expression)) { return declaration.expression.escapedText; @@ -101034,19 +101297,12 @@ var ts; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); - if (declaration.propertyName) { - return declaration.propertyName.escapedText; - } + return declaration.propertyName && declaration.propertyName.escapedText; } }); } }); - var addToExistingDeclaration = []; - var addNewDeclaration = []; - originalSymbolToExportInfos.forEach(function (exportInfos) { - getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration); - }); - return addToExistingDeclaration.concat(addNewDeclaration); + return originalSymbolToExportInfos; } function checkSymbolHasMeaning(_a, meaning) { var declarations = _a.declarations; @@ -101068,7 +101324,7 @@ var ts; for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { var sourceFile = allSourceFiles_1[_b]; if (ts.isExternalOrCommonJsModule(sourceFile)) { - cb(sourceFile.symbol, sourceFile); + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } @@ -101314,7 +101570,7 @@ var ts; if (token.parent.parent.kind === 199 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); // TODO: GH#18217 typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); @@ -101409,7 +101665,7 @@ var ts; var packageName = ts.getPackageName(moduleName).packageName; return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) - : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); + : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -101628,7 +101884,9 @@ var ts; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - doChange(changes, context.sourceFile, getInfo(diag.file, diag.start, diag.code)); + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); }); }, }); function getInfo(sourceFile, pos, diagCode) { @@ -101659,20 +101917,26 @@ var ts; ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { var errorCode = context.errorCode, sourceFile = context.sourceFile; - var importDecl = tryGetFullImport(sourceFile, context.span.start); + var startToken = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var importDecl = tryGetFullImport(startToken); if (importDecl) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } - var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start, /*deleted*/ undefined); }); + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, startToken, /*deleted*/ undefined); }); if (delDestructure.length) { return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(t, sourceFile, startToken, /*deleted*/ undefined); }); + if (delVar.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined); }); @@ -101688,9 +101952,10 @@ var ts; fixIds: [fixIdPrefix, fixIdDelete], getAllCodeActions: function (context) { // Track a set of deleted nodes that may be ancestors of other marked for deletion -- only delete the ancestors. - var deleted = new NodeSet(); + var deleted = new ts.NodeSet(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var sourceFile = context.sourceFile; + var startToken = ts.getTokenAtPosition(sourceFile, diag.start, /*includeJsDocComment*/ false); var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); switch (context.fixId) { case fixIdPrefix: @@ -101702,14 +101967,12 @@ var ts; // Ignore if this range was already deleted. if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); })) break; - var importDecl = tryGetFullImport(diag.file, diag.start); + var importDecl = tryGetFullImport(startToken); if (importDecl) { changes.deleteNode(sourceFile, importDecl); } - else { - if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) { - tryDeleteDeclaration(changes, sourceFile, token, deleted); - } + else if (!tryDeleteFullDestructure(changes, sourceFile, startToken, deleted) && !tryDeleteFullVariableStatement(changes, sourceFile, startToken, deleted)) { + tryDeleteDeclaration(changes, sourceFile, token, deleted); } break; default: @@ -101719,15 +101982,13 @@ var ts; }, }); // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. - function tryGetFullImport(sourceFile, pos) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + function tryGetFullImport(startToken) { return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; } - function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + function tryDeleteFullDestructure(changes, sourceFile, startToken, deletedAncestors) { if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent)) return false; - var decl = startToken.parent.parent; + var decl = ts.cast(startToken.parent, ts.isObjectBindingPattern).parent; switch (decl.kind) { case 231 /* VariableDeclaration */: tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors); @@ -101747,6 +102008,16 @@ var ts; } return true; } + function tryDeleteFullVariableStatement(changes, sourceFile, startToken, deletedAncestors) { + var declarationList = ts.tryCast(startToken.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === startToken) { + if (deletedAncestors) + deletedAncestors.add(declarationList); + changes.deleteNode(sourceFile, declarationList.parent.kind === 213 /* VariableStatement */ ? declarationList.parent : declarationList); + return true; + } + return false; + } function getToken(sourceFile, pos) { var token = ts.findPrecedingToken(pos, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); // this handles var ["computed"] = 12; @@ -101831,7 +102102,8 @@ var ts; // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + /*parameters*/ undefined, // TODO: GH#18217 + oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); // Drop leading and trailing trivia of the new function because we're only going // to replace the span (vs the full span) of the old function - the old leading // and trailing trivia will remain. @@ -101959,18 +102231,6 @@ var ts; } } } - var NodeSet = /** @class */ (function () { - function NodeSet() { - this.map = ts.createMap(); - } - NodeSet.prototype.add = function (node) { - this.map.set(String(ts.getNodeId(node)), node); - }; - NodeSet.prototype.some = function (pred) { - return ts.forEachEntry(this.map, pred) || false; - }; - return NodeSet; - }()); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -102034,6 +102294,8 @@ var ts; return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; case 237 /* EnumDeclaration */: return ts.hasModifier(s, 2048 /* Const */); + default: + return false; } } function sliceAfter(arr, value) { @@ -102120,7 +102382,7 @@ var ts; } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); @@ -102213,7 +102475,7 @@ var ts; default: return; } - return { + return insertBefore && { insertBefore: insertBefore, returnType: getReturnType(containingFunction) }; @@ -102508,7 +102770,7 @@ var ts; function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; + return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: @@ -102626,6 +102888,7 @@ var ts; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; }, reportInaccessibleThisError: notAccessible, @@ -102927,7 +103190,7 @@ var ts; return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { - var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); } @@ -102960,12 +103223,12 @@ var ts; } } if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); // TODO: GH#18217 } if (usageContext.stringIndexContext) { stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 } else { return undefined; @@ -103000,6 +103263,7 @@ var ts; parameters.push(symbol); } var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + // TODO: GH#18217 return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } function addCandidateType(context, type) { @@ -103008,7 +103272,7 @@ var ts; } } function hasCallContext(usageContext) { - return usageContext && usageContext.callContexts; + return !!usageContext && !!usageContext.callContexts; } })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); @@ -103041,7 +103305,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, context.preferences))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -103069,12 +103333,12 @@ var ts; return []; } var expr = node.expression; - var type = context.program.getTypeChecker().getTypeAtLocation(expr); + var type = context.program.getTypeChecker().getTypeAtLocation(expr); // TODO: GH#18217 if (!(type.symbol && type.symbol.originatingImport)) { return []; } var fixes = []; - var relatedImport = type.symbol.originatingImport; + var relatedImport = type.symbol.originatingImport; // TODO: GH#18217 if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } @@ -103151,8 +103415,9 @@ var ts; } 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)); + var type = propertyDeclaration.type; // TODO: GH#18217 + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); } function getActionForAddMissingInitializer(context, propertyDeclaration) { var checker = context.program.getTypeChecker(); @@ -103167,7 +103432,7 @@ var ts; changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { - return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 } function getDefaultValueFromType(checker, type) { if (type.flags & 2 /* String */) { @@ -103376,7 +103641,7 @@ var ts; // If the file is the main module, it can be imported by the package name var packageRootPath = path.substring(0, parts.packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { + if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); if (packageJsonContent) { var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; @@ -103461,7 +103726,7 @@ var ts; } function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } @@ -103527,14 +103792,14 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, 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); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { @@ -103550,8 +103815,8 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, preferences)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -103590,6 +103855,57 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + 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 token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var refactor; (function (refactor) { @@ -103672,7 +103988,7 @@ var ts; /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); - var targetRange = rangeToExtract.targetRange; + var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); if (parsedFunctionIndexMatch) { var index = +parsedFunctionIndexMatch[1]; @@ -103764,7 +104080,8 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; - for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { var errors_1 = checkNode(statement); @@ -103797,7 +104114,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -103897,6 +104214,9 @@ var ts; if (ts.isDeclaration(node)) { var declaringNode = (node.kind === 231 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { + // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) + // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! + // Also TODO: GH#19956 (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } @@ -103912,7 +104232,7 @@ var ts; // but a super *method call* simply implies a 'this' reference if (node.parent.kind === 186 /* CallExpression */) { // Super constructor call - var containingClass_1 = ts.getContainingClass(node); + var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; @@ -103923,7 +104243,7 @@ var ts; } break; } - if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { case 233 /* FunctionDeclaration */: case 234 /* ClassDeclaration */: @@ -104073,7 +104393,7 @@ var ts; function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - context.cancellationToken.throwIfCancellationRequested(); + context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217 return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { @@ -104170,7 +104490,7 @@ var ts; case 156 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: - ts.Debug.assertNever(scope); + throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { @@ -104238,7 +104558,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217 } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -104306,7 +104626,8 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), // TODO: GH#18217 + scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -104417,7 +104738,7 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -104433,7 +104754,7 @@ var ts; /*decorators*/ undefined, modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion - ? ts.createIdentifier(scope.name.getText()) + ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217 : ts.createThis(), ts.createIdentifier(localNameText)); // Declare var maxInsertionPos = node.pos; @@ -104527,7 +104848,7 @@ var ts; function getCalledExpression(scope, range, functionNameText) { var functionReference = ts.createIdentifier(functionNameText); if (ts.isClassLike(scope)) { - var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217 return ts.createPropertyAccess(lhs, functionReference); } else { @@ -104599,7 +104920,7 @@ var ts; } function getStatementsOrClassElements(scope) { if (ts.isFunctionLikeDeclaration(scope)) { - var body = scope.body; + var body = scope.body; // TODO: GH#18217 if (ts.isBlock(body)) { return body.statements; } @@ -104644,7 +104965,8 @@ var ts; } prevMember = member; } - ts.Debug.assert(prevMember !== undefined); // If the loop didn't return, then it did set prevMember. + if (prevMember === undefined) + return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember. return prevMember; } function getNodeToInsertConstantBefore(node, scope) { @@ -104671,18 +104993,15 @@ var ts; return curr.parent.parent; } // There must be at least one statement since we started in one. - ts.Debug.assert(prevStatement !== undefined); - return prevStatement; - } - if (curr === scope) { - ts.Debug.fail("Didn't encounter a block-like before encountering scope"); - break; + return ts.Debug.assertDefined(prevStatement); } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); } } function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + // TODO: GH#18217 `variableAssignments` not possibly undefined! return variableAssignments === undefined ? writeAssignments : writeAssignments === undefined @@ -104735,7 +105054,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { + else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { // TODO: GH#18217 expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -104768,7 +105087,7 @@ var ts; // will use the contextual type of an expression as the return type of the extracted // method (and will therefore "use" all the types involved). if (inGenericContext && !isReadonlyArray(targetRange.range)) { - var contextualType = checker.getContextualType(targetRange.range); + var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217 recordTypeParameterUsages(contextualType); } if (allTypeParameterUsages.size > 0) { @@ -104806,7 +105125,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_19 = function (i) { + var _loop_21 = 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 @@ -104846,7 +105165,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_19(i); + _loop_21(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -104868,7 +105187,7 @@ var ts; function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1 /* Read */; } if (inGenericContext) { - var type = checker.getTypeAtLocation(node); + var type = checker.getTypeAtLocation(node); // TODO: GH#18217 recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { @@ -105071,22 +105390,23 @@ var ts; * in the sense of something that you could extract on */ function isExtractableExpression(node) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 272 /* EnumMember */: return false; } switch (node.kind) { case 9 /* StringLiteral */: - return node.parent.kind !== 243 /* ImportDeclaration */ && - node.parent.kind !== 247 /* ImportSpecifier */; + return parent.kind !== 243 /* ImportDeclaration */ && + parent.kind !== 247 /* ImportSpecifier */; case 203 /* SpreadElement */: case 179 /* ObjectBindingPattern */: case 181 /* BindingElement */: return false; case 71 /* Identifier */: - return node.parent.kind !== 181 /* BindingElement */ && - node.parent.kind !== 247 /* ImportSpecifier */ && - node.parent.kind !== 251 /* ExportSpecifier */; + return parent.kind !== 181 /* BindingElement */ && + parent.kind !== 247 /* ImportSpecifier */ && + parent.kind !== 251 /* ExportSpecifier */; } return true; } @@ -105172,7 +105492,7 @@ var ts; var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } - function isConvertableName(name) { + function isConvertibleName(name) { return ts.isIdentifier(name) || ts.isStringLiteral(name); } function isAcceptedDeclaration(node) { @@ -105182,7 +105502,7 @@ var ts; return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name); } function createAccessorAccessExpression(fieldName, isStatic, container) { - var leftHead = isStatic ? container.name : ts.createThis(); + var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217 return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); } function getModifiers(isJS, isStatic, accessModifier) { @@ -105198,8 +105518,8 @@ var ts; var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; - if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) - || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) // TODO: GH#18217 + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; var name = declaration.name.text; var startWithUnderscore = startsWithUnderscore(name); @@ -105220,7 +105540,8 @@ var ts; function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { return ts.createGetAccessor( /*decorators*/ undefined, modifiers, accessorName, - /*parameters*/ undefined, type, ts.createBlock([ + /*parameters*/ undefined, // TODO: GH#18217 + type, ts.createBlock([ ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container)) ], /*multiLine*/ true)); } @@ -105264,7 +105585,9 @@ var ts; if (!constructor.body) return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; - var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); }); + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { + return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; var accessorName = ts.createIdentifier(fieldName.text); @@ -105287,7 +105610,7 @@ var ts; var refactorName = "Move to a new file"; refactor.registerRefactor(refactorName, { getAvailableActions: function (context) { - if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined) + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; @@ -105295,27 +105618,31 @@ var ts; getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === refactorName); var statements = ts.Debug.assertDefined(getStatementsToMove(context)); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - function getFirstAndLastStatementToMove(context) { + function getRangeToMove(context) { var file = context.file; var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); var statements = file.statements; var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); if (startNodeIndex === -1) return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return [statements[startNodeIndex]]; + } // Can't only partially include the start node or be partially into the next node - if (range.pos > statements[startNodeIndex].getStart(file)) + if (range.pos > startStatement.getStart(file)) return undefined; var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); // Can't be partially into the next node if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex }; + return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); } - function doChange(oldFile, program, toMove, changes, host) { + function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); @@ -105323,22 +105650,22 @@ var ts; var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. - changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); } // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. function getStatementsToMove(context) { - var statements = context.file.statements; - var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast; + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; var all = []; var ranges = []; - var rangeToMove = statements.slice(first, afterLast); ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) { for (var i = start; i < afterEnd; i++) all.push(rangeToMove[i]); ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] }); }); - return { all: all, ranges: ranges }; + return all.length === 0 ? undefined : { all: all, ranges: ranges }; } function isPureImport(node) { switch (node.kind) { @@ -105347,7 +105674,7 @@ var ts; case 242 /* ImportEqualsDeclaration */: return !ts.hasModifier(node, 1 /* Export */); case 213 /* VariableStatement */: - return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; } @@ -105366,26 +105693,26 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) { + function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { deleteMovedStatements(oldFile, toMove.ranges, changes); return toMove.all; } var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, preferences); if (importsFromNewFile) { changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); } function deleteMovedStatements(sourceFile, moved, changes) { for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { - var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last; - changes.deleteNodeRange(sourceFile, first_1, last_3); + var _a = moved_1[_i], first_1 = _a.first, last_2 = _a.last; + changes.deleteNodeRange(sourceFile, first_1, last_2); } } function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { @@ -105398,15 +105725,15 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_20 = function (sourceFile) { + var _loop_22 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_21 = function (statement) { + var _loop_23 = function (statement) { forEachImportInStatement(statement, function (importNode) { var shouldMove = function (name) { var symbol = ts.isBindingElement(name.parent) ? ts.getPropertySymbolFromBindingElement(checker, name.parent) - : ts.skipAlias(checker.getSymbolAtLocation(name), checker); + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217 return !!symbol && movedSymbols.has(symbol); }; deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file @@ -105418,12 +105745,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_21(statement); + _loop_23(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_20(sourceFile); + _loop_22(sourceFile); } } function moduleSpecifierFromImport(i) { @@ -105450,24 +105777,24 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { if (symbol.escapedName === "default" /* Default */) { - defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217 } else { imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { path = ts.ensurePathIsNonModuleName(path); if (useEs6Imports) { var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); - return ts.makeImportIfNecessary(defaultImport, specifiers, path); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, preferences); } else { ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. @@ -105566,7 +105893,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -105598,7 +105925,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -105606,7 +105933,7 @@ var ts; for (var i = 1;; i++) { var name = ts.combinePaths(inDirectory, newModuleName + extension); if (!host.fileExists(name)) - return newModuleName; + return newModuleName; // TODO: GH#18217 newModuleName = moduleName + "." + i; } } @@ -105857,7 +106184,7 @@ var ts; switch (decl.kind) { case 233 /* FunctionDeclaration */: case 234 /* ClassDeclaration */: - return [decl.name.text]; + return [decl.name.text]; // TODO: GH#18217 case 213 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); case 238 /* ModuleDeclaration */: @@ -105865,11 +106192,11 @@ var ts; case 236 /* TypeAliasDeclaration */: case 235 /* InterfaceDeclaration */: case 242 /* ImportEqualsDeclaration */: - return undefined; + return ts.emptyArray; case 215 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: - ts.Debug.assertNever(decl); + return ts.Debug.assertNever(decl); } } /** Creates `exports.x = x;` */ @@ -106089,7 +106416,7 @@ var ts; var value = 0; for (; moreDigits; state.decodingIndex++) { if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return; + return undefined; // TODO: GH#18217 } // 6 digit number var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); @@ -106139,7 +106466,7 @@ var ts; this.pos = pos; this.end = end; this.flags = 0 /* None */; - this.transformFlags = undefined; + this.transformFlags = undefined; // TODO: GH#18217 this.parent = undefined; this.kind = kind; } @@ -106325,7 +106652,7 @@ var ts; return 0; }; TokenOrIdentifierObject.prototype.getChildAt = function () { - return undefined; + return undefined; // TODO: GH#18217 }; TokenOrIdentifierObject.prototype.getChildren = function () { return ts.emptyArray; @@ -106517,9 +106844,9 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); @@ -106823,7 +107150,7 @@ var ts; }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; + return ts.isString(info) ? undefined : info; // TODO: GH#18217 }; HostCache.prototype.getRootFileNames = function () { var names = []; @@ -106841,11 +107168,11 @@ var ts; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); - return file && file.version; + return (file && file.version); // TODO: GH#18217 }; HostCache.prototype.getScriptSnapshot = function (path) { var file = this.getHostFileInformation(path); - return file && file.scriptSnapshot; + return (file && file.scriptSnapshot); // TODO: GH#18217 }; return HostCache; }()); @@ -106948,7 +107275,7 @@ var ts; this.cancellationToken = cancellationToken; } CancellationTokenObject.prototype.isCancellationRequested = function () { - return this.cancellationToken && this.cancellationToken.isCancellationRequested(); + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { @@ -106998,7 +107325,7 @@ var ts; if (!host.fileExists || !host.readFile || !host.fileExists(path)) return; // And failing that, check the disk - var text = host.readFile(path); + var text = host.readFile(path); // TODO: GH#18217 var file = { text: text, lineMap: undefined, @@ -107056,7 +107383,7 @@ var ts; var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; if (lastTypesRootVersion !== typeRootsVersion) { log("TypeRoots version has changed; provide new program"); - program = undefined; + program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } // Get a fresh cache of the host information @@ -107064,7 +107391,7 @@ var ts; var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -107141,7 +107468,7 @@ var ts; var entry = hostCache.getEntryByPath(path); return entry ? !ts.isString(entry) : - (host.fileExists && host.fileExists(fileName)); + (!!host.fileExists && host.fileExists(fileName)); } // Release any files we have acquired in the old program but are // not part of the new program. @@ -107201,6 +107528,7 @@ var ts; return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } + // TODO: GH#18217 frequently asserted as defined function getProgram() { if (syntaxOnly) { ts.Debug.assert(program === undefined); @@ -107210,14 +107538,14 @@ var ts; return program; } function cleanupSemanticCache() { - program = undefined; + program = undefined; // TODO: GH#18217 } function dispose() { if (program) { ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); - program = undefined; + program = undefined; // TODO: GH#18217 } host = undefined; } @@ -107261,7 +107589,8 @@ var ts; function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { if (preferences === void 0) { preferences = ts.defaultPreferences; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName, preferences, cancellationToken); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + getCanonicalFileName, preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -107330,7 +107659,7 @@ var ts; } function toLineColumnOffset(fileName, position) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); + var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) @@ -107397,7 +107726,7 @@ var ts; var location = possibleMapLocations_1[_i]; var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 } } return file.sourceMapper = ts.sourcemaps.identitySourceMapper; @@ -107529,11 +107858,13 @@ var ts; } /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); @@ -107560,7 +107891,7 @@ var ts; // Get node at the location var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { - return; + return undefined; } switch (node.kind) { case 184 /* PropertyAccessExpression */: @@ -107576,7 +107907,7 @@ var ts; break; // Cant create the text span default: - return; + return undefined; } var nodeForStartPos = node; while (true) { @@ -107739,7 +108070,7 @@ var ts; ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); default: - ts.Debug.fail(); + return ts.Debug.fail(); // TODO: Debug.assertNever(action); will only work if there is more than one type. } } @@ -107830,7 +108161,8 @@ var ts; descriptor = descriptors[i]; } } - ts.Debug.assert(descriptor !== undefined); + if (descriptor === undefined) + return ts.Debug.fail(); // We don't want to match something like 'TODOBY', so we make sure a non // letter/digit follows the match. if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { @@ -107995,7 +108327,7 @@ var ts; if (!sourceFile.nameTable) { initializeNameTable(sourceFile); } - return sourceFile.nameTable; + return sourceFile.nameTable; // TODO: GH#18217 } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { @@ -108049,8 +108381,8 @@ var ts; /* @internal */ function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); - return getPropertySymbolsFromType(contextualType, node.name); + var contextualType = typeChecker.getContextualType(objectLiteral); // TODO: GH#18217 + return getPropertySymbolsFromType(contextualType, node.name); // TODO: GH#18217 } ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; /* @internal */ @@ -108118,11 +108450,12 @@ var ts; // let y = 10; // token at position will return let keyword on second line as the token but we would like to use // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line - tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); // It's a blank line - if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { return undefined; } + tokenAtLocation = preceding; } // Cannot set breakpoint in ambient declarations if (tokenAtLocation.flags & 4194304 /* Ambient */) { @@ -108156,6 +108489,7 @@ var ts; } function spanInNode(node) { if (node) { + var parent = node.parent; switch (node.kind) { case 213 /* VariableStatement */: // Span on first variable declaration @@ -108258,7 +108592,7 @@ var ts; // span in statement return spanInNode(node.statement); case 149 /* Decorator */: - return spanInNodeArray(node.parent.decorators); + return spanInNodeArray(parent.decorators); case 179 /* ObjectBindingPattern */: case 180 /* ArrayBindingPattern */: return spanInBindingPattern(node); @@ -108310,7 +108644,7 @@ var ts; node.kind === 203 /* SpreadElement */ || node.kind === 269 /* PropertyAssignment */ || node.kind === 270 /* ShorthandPropertyAssignment */) && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } if (node.kind === 199 /* BinaryExpression */) { @@ -108334,7 +108668,7 @@ var ts; } } if (ts.isExpressionNode(node)) { - switch (node.parent.kind) { + switch (parent.kind) { case 217 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); @@ -108414,6 +108748,7 @@ var ts; if (variableDeclaration.parent.parent.kind === 220 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } + var parent = variableDeclaration.parent; // If this is a destructuring pattern, set breakpoint in binding pattern if (ts.isBindingPattern(variableDeclaration.name)) { return spanInBindingPattern(variableDeclaration.name); @@ -108422,7 +108757,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - variableDeclaration.parent.parent.kind === 221 /* ForOfStatement */) { + parent.parent.kind === 221 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -108709,7 +109044,7 @@ var ts; */ function transform(source, transformers, compilerOptions) { var diagnostics = []; - compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); + compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217 var nodes = ts.isArray(source) ? source : [source]; var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); @@ -108758,16 +109093,16 @@ var ts; var oldSnapshotShim = oldSnapshot; var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); if (encoded === null) { - return null; + return null; // TODO: GH#18217 } - var decoded = JSON.parse(encoded); + var decoded = JSON.parse(encoded); // TODO: GH#18217 return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; ScriptSnapshotShimAdapter.prototype.dispose = function () { // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments // 'in' does not have this effect if ("dispose" in this.scriptSnapshotShim) { - this.scriptSnapshotShim.dispose(); + this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`? } }; return ScriptSnapshotShimAdapter; @@ -108782,10 +109117,10 @@ var ts; // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { this.resolveModuleNames = function (moduleNames, containingFile) { - var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217 }); }; } @@ -108794,8 +109129,8 @@ var ts; } if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217 }; } } @@ -108815,7 +109150,7 @@ var ts; LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { if (!this.shimHost.getProjectVersion) { // shimmed host does not support getProjectVersion - return undefined; + return undefined; // TODO: GH#18217 } return this.shimHost.getProjectVersion(); }; @@ -108848,7 +109183,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { if ("getScriptKind" in this.shimHost) { - return this.shimHost.getScriptKind(fileName); + return this.shimHost.getScriptKind(fileName); // TODO: GH#18217 } else { return 0 /* Unknown */; @@ -108884,7 +109219,7 @@ var ts; return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { @@ -108905,11 +109240,11 @@ var ts; this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } if ("realpath" in this.shimHost) { - this.realpath = function (path) { return _this.shimHost.realpath(path); }; + this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -108981,7 +109316,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = /** @class */ (function (_super) { @@ -109287,10 +109623,12 @@ var ts; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); var result = ""; for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index ab3cb0310f4..4976114991f 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -179,7 +179,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.9"; + ts.versionMajorMinor = "3.0"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { @@ -450,7 +450,7 @@ var ts; return result; } } - Debug.fail(); + return Debug.fail(); } ts.findMap = findMap; function contains(array, value, equalityComparer) { @@ -980,15 +980,6 @@ var ts; return to; } ts.addRange = addRange; - function prependRange(to, from) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(); - to.unshift.apply(to, from); - return to; - } - ts.prependRange = prependRange; function pushIfUnique(array, toAdd, equalityComparer) { if (contains(array, toAdd, equalityComparer)) { return false; @@ -1381,10 +1372,10 @@ var ts; if (value !== undefined && test(value)) return value; if (value && typeof value.kind === "number") { - Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); } else { - Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + return Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } } ts.cast = cast; @@ -1464,7 +1455,7 @@ var ts; } ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { - baseIndex = baseIndex || 0; + if (baseIndex === void 0) { baseIndex = 0; } return text.replace(/{(\d+)}/g, function (_match, index) { return Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; @@ -1701,7 +1692,9 @@ var ts; return compareValues(a ? 1 : 0, b ? 1 : 0); } ts.compareBooleans = compareBooleans; - function compareMessageText(text1, text2) { + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; while (text1 && text2) { var string1 = isString(text1) ? text1 : text1.messageText; var string2 = isString(text2) ? text2 : text2.messageText; @@ -1735,6 +1728,14 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { return !!(options.declaration && options.declarationMap); } @@ -1753,7 +1754,7 @@ var ts; } ts.getEmitDeclarations = getEmitDeclarations; function getStrictOptionValue(compilerOptions, flag) { - return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { @@ -2213,7 +2214,7 @@ var ts; var subpattern = ""; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); - var lastComponent = lastOrUndefined(components); + var lastComponent = last(components); if (usage !== "exclude" && lastComponent === "**") { return undefined; } @@ -2404,11 +2405,11 @@ var ts; return scriptKind === 1 || scriptKind === 2; } function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + return some(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { @@ -2582,7 +2583,8 @@ var ts; } Debug.fail = fail; function assertDefined(value, message) { - assert(value !== undefined && value !== null, message); + if (value === undefined || value === null) + return fail(message); return value; } Debug.assertDefined = assertDefined; @@ -2740,10 +2742,7 @@ var ts; ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); - if (ext !== undefined) { - return ext; - } - Debug.fail("File " + path + " has unknown extension."); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); } ts.extensionFromPath = extensionFromPath; function isAnySupportedFileExtension(path) { @@ -3292,6 +3291,7 @@ var ts; return watchDirectoryRecursively(directoryName, callback); } watchDirectory(directoryName, callback); + return undefined; }; } function createNonPollingWatchFile() { @@ -3522,6 +3522,7 @@ var ts; switch (entryKind) { case 0: return stat.isFile(); case 1: return stat.isDirectory(); + default: return false; } } catch (e) { @@ -4204,7 +4205,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -4532,6 +4533,8 @@ var ts; _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true), Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", true), + Enable_strict_checking_of_any_type: diag(6200, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_any_type_6200", "Enable strict checking of 'any' type."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -4559,7 +4562,7 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", true), Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), @@ -4640,6 +4643,7 @@ var ts; Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -4709,6 +4713,7 @@ var ts; Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), }; })(ts || (ts = {})); var ts; @@ -4806,7 +4811,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function packageIdToString(_a) { var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; @@ -4913,6 +4918,19 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + function prependStatements(to, from) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(); + var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); + to.unshift.apply(to, from); + if (prologue) { + to.unshift(prologue); + } + return to; + } + ts.prependStatements = prependStatements; function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { if (text.charCodeAt(commentPos + 1) === 47 && commentPos + 2 < commentEnd && @@ -4982,7 +5000,7 @@ var ts; ts.indexOfNode = indexOfNode; function getEmitFlags(node) { var emitNode = node.emitNode; - return emitNode && emitNode.flags; + return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { @@ -5010,7 +5028,7 @@ var ts; case 12: return node.text; } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { @@ -5104,7 +5122,7 @@ var ts; case 192: return true; case 212: - return parentNode && !ts.isFunctionLike(parentNode); + return !ts.isFunctionLike(parentNode); } return false; } @@ -5205,6 +5223,8 @@ var ts; return entityNameToString(name.left) + "." + entityNameToString(name.right); case 184: return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); } } ts.entityNameToString = entityNameToString; @@ -5399,7 +5419,7 @@ var ts; ts.Debug.assert(node.kind === 71 || node.kind === 145 || node.kind === 184, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 145: case 184: - case 99: + case 99: { var parent = node.parent; if (parent.kind === 164) { return false; @@ -5441,6 +5461,7 @@ var ts; case 188: return false; } + } } return false; } @@ -5621,15 +5642,16 @@ var ts; return ts.filter(objectLiteral.properties, function (property) { if (property.kind === 269) { var propName = getTextOfPropertyName(property.name); - return key === propName || (key2 && key2 === propName); + return key === propName || (!!key2 && key2 === propName); } + return false; }); } ts.getPropertyAssignment = getPropertyAssignment; function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { var expression = tsConfigSourceFile.statements[0].expression; - return ts.isObjectLiteralExpression(expression) && expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); } } ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; @@ -5652,10 +5674,11 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 273); while (true) { node = node.parent; if (!node) { - return undefined; + return ts.Debug.fail(); } switch (node.kind) { case 146: @@ -5831,10 +5854,12 @@ var ts; function childIsDecorated(node, parent) { switch (node.kind) { case 234: - return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); case 153: case 156: - return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + default: + return false; } } ts.childIsDecorated = childIsDecorated; @@ -5977,15 +6002,15 @@ var ts; } ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536); + return !!node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; function isInJsonFile(node) { - return node && !!(node.flags & 16777216); + return !!node && !!(node.flags & 16777216); } ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { - return node && !!(node.flags & 2097152); + return !!node && !!(node.flags & 2097152); } ts.isInJSDoc = isInJSDoc; function isJSDocIndexSignature(node) { @@ -6209,7 +6234,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 243 && node.importClause && !!node.importClause.name; + return node.kind === 243 && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { @@ -6246,16 +6271,18 @@ var ts; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 && - node.expression.right; + node.expression.operatorToken.kind === 58 + ? node.expression.right + : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && getSpecialPropertyAssignmentKind(node.expression) !== 0 && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 && - node.expression.right.right; + node.expression.right.operatorToken.kind === 54 + ? node.expression.right.right + : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { @@ -6269,15 +6296,14 @@ var ts; } } function getSingleVariableOfVariableStatement(node) { - return ts.isVariableStatement(node) && - node.declarationList.declarations.length > 0 && - node.declarationList.declarations[0]; + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } function getNestedModuleDeclaration(node) { - return node.kind === 238 && + return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 238 && - node.body; + node.body.kind === 238 + ? node.body + : undefined; } function getJSDocCommentsAndTags(hostNode) { var result; @@ -6358,12 +6384,12 @@ var ts; ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { var last = ts.lastOrUndefined(s.parameters); - return last && isRestParameter(last); + return !!last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || type && type.kind === 284; + return node.dotDotDotToken !== undefined || !!type && type.kind === 284; } ts.isRestParameter = isRestParameter; function getAssignmentTargetKind(node) { @@ -6484,9 +6510,10 @@ var ts; switch (name.kind) { case 71: case 9: - case 8: - if (ts.isDeclaration(name.parent)) { - return name.parent.name === name; + case 8: { + var parent = name.parent; + if (ts.isDeclaration(parent)) { + return parent.name === name; } else if (ts.isQualifiedName(name.parent)) { var tag = name.parent.parent; @@ -6496,6 +6523,7 @@ var ts; var binExp = name.parent.parent; return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; } + } default: return false; } @@ -6670,7 +6698,7 @@ var ts; ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); - return name && isDynamicName(name); + return !!name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -7097,7 +7125,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); + linePos = output.length - s.length + ts.last(lineStartsOfS); } } } @@ -7256,7 +7284,7 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return node && node.kind === 71 && identifierIsThisKeyword(node); + return !!node && node.kind === 71 && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { @@ -7425,12 +7453,12 @@ var ts; lastComment = comment; } if (detachedComments.length) { - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; } } } @@ -7573,7 +7601,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 206 && + if (ts.isExpressionWithTypeArguments(node) && node.parent.token === 85 && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -8348,7 +8376,7 @@ var ts; try { ts.localizedDiagnosticMessages = JSON.parse(fileContents); } - catch (e) { + catch (_a) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); } @@ -9906,7 +9934,8 @@ var ts; } ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { - return !!node.jsDoc && node.jsDoc.length > 0; + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; function hasType(node) { @@ -10599,8 +10628,9 @@ var ts; return true; } ts.isIdentifierText = isIdentifierText; - function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } + var text = textInitial; var pos; var end; var startPos; @@ -12214,6 +12244,7 @@ var ts; } ts.isExternalModule = isExternalModule; function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); newSourceFile.flags |= (sourceFile.flags & 1572864); return newSourceFile; @@ -12251,6 +12282,7 @@ var ts; var contextFlags; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); @@ -12432,6 +12464,7 @@ var ts; nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -12859,7 +12892,7 @@ var ts; case 14: return true; } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17); @@ -12935,6 +12968,8 @@ var ts; return token() === 29 || token() === 41; case 14: return token() === 27 && lookAhead(nextTokenIsSlash); + default: + return false; } } function isVariableDeclaratorListTerminator() { @@ -13179,6 +13214,7 @@ var ts; case 22: return ts.Diagnostics.Identifier_expected; case 13: return ts.Diagnostics.Identifier_expected; case 14: return ts.Diagnostics.Identifier_expected; + default: return undefined; } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -13269,7 +13305,7 @@ var ts; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(list).literal.kind === 15); + } while (ts.last(list).literal.kind === 15); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } @@ -13577,7 +13613,7 @@ var ts; if (token() === 19 || token() === 27) { return true; } - var idToken; + var idToken = false; while (ts.isModifierKind(token())) { idToken = true; nextToken(); @@ -15576,6 +15612,7 @@ var ts; missing.modifiers = node.modifiers; return finishNode(missing); } + return undefined; } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { @@ -15866,7 +15903,7 @@ var ts; node.name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(node); } - ts.Debug.fail("Should not have attempted to parse class member declaration."); + return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 204); @@ -15905,14 +15942,12 @@ var ts; } function parseHeritageClause() { var tok = token(); - if (tok === 85 || tok === 108) { - var node = createNode(267); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; + ts.Debug.assert(tok === 85 || tok === 108); + var node = createNode(267); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); + return finishNode(node); } function parseExpressionWithTypeArguments() { var node = createNode(206); @@ -16253,8 +16288,8 @@ var ts; } JSDocParser.parseJSDocComment = parseJSDocComment; function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } var content = sourceText; - start = start || 0; var end = length === undefined ? content.length : start + length; length = end - start; ts.Debug.assert(start >= 0); @@ -16557,7 +16592,7 @@ var ts; var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target); + var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -17266,10 +17301,7 @@ var ts; break; } case "amd-dependency": { - context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { - var _b = _a.arguments, name = _b.name, path = _b.path; - return ({ name: name, path: path }); - }); + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); break; } case "amd-module": { @@ -17685,6 +17717,13 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, }, + { + name: "strictAny", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_any_type + }, { name: "strictNullChecks", type: "boolean", @@ -18169,7 +18208,7 @@ var ts; case "string": return ts.map(values, function (v) { return v || ""; }); default: - return ts.filter(ts.map(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }), function (v) { return !!v; }); + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); } } ts.parseListTypeOption = parseListTypeOption; @@ -18548,6 +18587,7 @@ var ts; var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } + return false; } function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); @@ -18969,13 +19009,10 @@ var ts; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return undefined; + return false; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; + return typeof result === "boolean" && result; } function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; @@ -19004,7 +19041,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -19278,7 +19315,7 @@ var ts; } ts.trace = trace; function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; + return !!compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; function withPackageId(packageId, r) { @@ -19439,14 +19476,13 @@ var ts; } } function secondaryLookup() { - var resolvedFile; var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); + var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -19598,7 +19634,7 @@ var ts; result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; default: - ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -19776,7 +19812,7 @@ var ts; var originalPath = void 0; if (!compilerOptions.preserveSymlinks && resolvedValue) { originalPath = resolvedValue.path; - var path = realPath(resolved_1.value.path, host, traceEnabled); + var path = realPath(resolvedValue.path, host, traceEnabled); if (path === originalPath) { originalPath = undefined; } @@ -19876,7 +19912,7 @@ var ts; function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json"); - return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); } var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -19910,7 +19946,7 @@ var ts; } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, ext: ext }; + return path === undefined ? undefined : { path: path, ext: ext }; } } function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { @@ -20499,7 +20535,7 @@ var ts; case 0: return ts.Debug.fail(); default: - ts.Debug.assertNever(result); + throw ts.Debug.assertNever(result); } } JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index b92e4727075..69da659c250 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "向属性“{0}”添加初始值设定项", "Add_initializers_to_all_uninitialized_properties_95027": "将初始化表达式添加到未初始化的所有属性", "Add_missing_super_call_90001": "添加缺失的 \"super()\" 调用", + "Add_missing_typeof_95052": "添加缺少的 \"typeof\"", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "将限定符添加到匹配成员名称的所有未解析变量", "Add_to_all_uncalled_decorators_95044": "将 \"()\" 添加到所有未调用的修饰器", "Add_ts_ignore_to_all_error_messages_95042": "将 \"@ts-ignore\" 添加到所有错误消息", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有声明必须是连续的。", "All_destructured_elements_are_unused_6198": "未取消使用任何解构元素。", "All_imports_in_import_declaration_are_unused_6192": "未使用导入声明中的所有导入。", + "All_variables_are_unused_6199": "所有变量均未使用。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允许从不带默认输出的模块中默认输入。这不会影响代码发出,只是类型检查。", "Allow_javascript_files_to_be_compiled_6102": "允许编译 JavaScript 文件。", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "提供 \"--isolatedModules\" 标志的情况下不允许使用环境常数枚举。", @@ -273,6 +275,7 @@ "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "类“{0}”的构造函数是受保护的,仅可在类声明中访问。", "Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生类的构造函数必须包含 \"super\" 调用。", "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含文件,并且无法确定根目录,正在跳过在 \"node_modules\" 文件夹中查找。", + "Convert_0_to_mapped_object_type_95055": "Convert '{0}' to mapped object type", "Convert_all_constructor_functions_to_classes_95045": "将所有构造函数都转换为类", "Convert_all_require_to_import_95048": "将所有 \"require\" 转换为 \"import\"", "Convert_all_to_default_imports_95035": "全部转换为默认导入", @@ -708,10 +711,13 @@ "Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "引用的项目“{0}”必须拥有设置 \"composite\": true。", "Remove_all_unreachable_code_95051": "删除所有无法访问的代码", + "Remove_all_unused_labels_95054": "删除所有未使用的标签", "Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明", "Remove_destructuring_90009": "删除解构", "Remove_import_from_0_90005": "从“{0}”删除导入", "Remove_unreachable_code_95050": "删除无法访问的代码", + "Remove_unused_label_95053": "删除未使用的标签", + "Remove_variable_statement_90010": "删除变量语句", "Replace_import_with_0_95015": "用“{0}”替换导入。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "在函数中的所有代码路径并非都返回值时报告错误。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "报告 switch 语句中遇到 fallthrough 情况的错误。", diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index f250984e6f2..6a1c71d7a6a 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -106,6 +106,7 @@ "Add_initializer_to_property_0_95019": "將初始設定式新增至屬性 '{0}'", "Add_initializers_to_all_uninitialized_properties_95027": "為所有未初始化的屬性新增初始設定式", "Add_missing_super_call_90001": "新增遺漏的 'super()' 呼叫", + "Add_missing_typeof_95052": "新增遺漏的 'typeof'", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "對所有比對成員名稱的未解析變數新增限定詞", "Add_to_all_uncalled_decorators_95044": "為所有未呼叫的裝飾項目新增 '()'", "Add_ts_ignore_to_all_error_messages_95042": "為所有錯誤訊息新增 '@ts-ignore'", @@ -119,6 +120,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。", "All_destructured_elements_are_unused_6198": "不會使用所有未經結構化的項目。", "All_imports_in_import_declaration_are_unused_6192": "匯入宣告中的所有匯入皆未使用。", + "All_variables_are_unused_6199": "所有變數都未使用。", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允許從沒有預設匯出的模組進行預設匯入。這不會影響程式碼發出,僅為類型檢查。", "Allow_javascript_files_to_be_compiled_6102": "允許編譯 JavaScript 檔案。", "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "提供 '--isolatedModules' 旗標時,不可使用環境常數列舉。", @@ -708,10 +710,13 @@ "Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "參考的專案 '{0}' 之設定 \"composite\" 必須為 true。", "Remove_all_unreachable_code_95051": "移除所有無法連線的程式碼", + "Remove_all_unused_labels_95054": "移除所有未使用的標籤", "Remove_declaration_for_Colon_0_90004": "移除 '{0}' 的宣告", "Remove_destructuring_90009": "移除解構", "Remove_import_from_0_90005": "從 '{0}' 移除匯入", "Remove_unreachable_code_95050": "移除無法連線的程式碼", + "Remove_unused_label_95053": "移除未使用的標籤", + "Remove_variable_statement_90010": "移除變數陳述式", "Replace_import_with_0_95015": "以 '{0}' 取代匯入。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "當函式中的部分程式碼路徑並未傳回值時回報錯誤。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "回報 switch 陳述式內 fallthrough 案例的錯誤。",