diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 221882e80f6d5..9e6dfccdf8491 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -4351,8 +4351,8 @@ declare namespace Intl { interface DateTimeFormatOptions { localeMatcher?: "best fit" | "lookup"; - weekday?: "long" | "short" | "narrow"; - era?: "long" | "short" | "narrow"; + weekday?: "long" | "short" | "narrow"; + era?: "long" | "short" | "narrow"; year?: "numeric" | "2-digit"; month?: "numeric" | "2-digit" | "long" | "short" | "narrow"; day?: "numeric" | "2-digit"; diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 22e0d7f857e8c..4aa1a3b7df2aa 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -2516,6 +2516,7 @@ declare namespace ts.server.protocol { readonly provideRefactorNotApplicableReason?: boolean; readonly allowRenameOfImportPath?: boolean; readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; + readonly generateReturnInDocTemplate?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/tsc.js b/lib/tsc.js index 42419ac12a345..f40025ec38f85 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -2708,40 +2708,41 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); + } + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); } - }, - PerformanceObserver: PerformanceObserver_1 + } }; } return { + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -2766,7 +2767,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; var performanceImpl; function createTimerIf(condition, measureName, startMarkName, endMarkName) { return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; @@ -2795,14 +2795,30 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; function getCount(markName) { @@ -2818,38 +2834,35 @@ var ts; } performance.forEachMeasure = forEachMeasure; function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; @@ -2889,28 +2902,27 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var tracing; - (function (tracing) { +})(ts || (ts = {})); +(function (ts) { + var tracingEnabled; + (function (tracingEnabled) { var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; var legendPath; var legend = []; ; function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); @@ -2918,9 +2930,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 ? "." + process.pid + "-" + ++traceCount : - mode === 2 ? "." + process.pid : - ""; + var countPart = mode === 1 ? "." + process.pid + "-" + ++traceCount + : mode === 2 ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -2929,22 +2941,19 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; + tracingEnabled.startTracing = startTracing; function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); ts.Debug.assert(!!typeCatalog === (mode !== 2)); fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; + ts.tracing = undefined; if (typeCatalog) { dumpTypes(typeCatalog); } @@ -2952,59 +2961,46 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; - } - tracing.isTracing = isTracing; + tracingEnabled.stopTracing = stopTracing; function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, undefined, endTime); } - else { + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); if (mode === 2 && phase === "checkTypes") return; ts.performance.mark("beginTracing"); @@ -3025,7 +3021,6 @@ var ts; } function dumpTypes(types) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3101,11 +3096,13 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled = ts.tracingEnabled || (ts.tracingEnabled = {})); +})(ts || (ts = {})); +(function (ts) { + ts.startTracing = ts.tracingEnabled.startTracing; })(ts || (ts = {})); var ts; (function (ts) { @@ -4492,6 +4489,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -4694,7 +4692,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -4976,7 +4974,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -5237,6 +5235,8 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", undefined, true), @@ -5706,6 +5706,9 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5778,6 +5781,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -5850,6 +5854,7 @@ var ts; The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -6118,8 +6123,9 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", undefined, undefined, true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", undefined, undefined, true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", undefined, undefined, true), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -7108,6 +7114,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -8061,15 +8068,9 @@ var ts; } return token = 79; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -8086,6 +8087,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31) { if (text.charCodeAt(pos) === 62) { @@ -8704,8 +8730,10 @@ var ts; return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -8714,7 +8742,7 @@ var ts; } var language = matchResult[1]; var territory = matchResult[3]; - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, undefined, errors); } ts.setUILocale(locale); @@ -12078,6 +12106,8 @@ var ts; return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; case 203: return node.arguments[0]; + case 256: + return node.name.kind === 10 ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -13358,11 +13388,19 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -13948,6 +13986,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -14557,7 +14601,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -14898,6 +14942,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -14959,19 +15007,30 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + } }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); + var cache = createSymlinkCache(cwd, getCanonicalFileName); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; @@ -14981,15 +15040,15 @@ var ts; var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -15312,6 +15371,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (ts.fileExtensionIs(path, supportedExtensions[i])) { @@ -15710,6 +15777,10 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; })(ts || (ts = {})); var ts; (function (ts) { @@ -22959,62 +23030,57 @@ var ts; } ts.forEachChild = forEachChild; function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 157) { + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse", "createSourceFile", { path: fileName }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse", "createSourceFile", { path: fileName }, true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -23027,7 +23093,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -23708,8 +23774,8 @@ var ts; return identifier; } function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); var originalKeywordKind = token(); var text = internIdentifier(scanner.getTokenValue()); @@ -23720,6 +23786,10 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(true); } + if (token() === 0 && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78; })) { + return createIdentifier(true); + } + identifierCount++; var reportAtCurrentPosition = token() === 1; var isReservedWord = scanner.isReservedWord(); var msgArg = scanner.getTokenText(); @@ -27868,6 +27938,7 @@ var ts; function parseTagComments(indent, initialMargin) { var comments = []; var state = 0; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -27891,7 +27962,7 @@ var ts; indent = 0; break; case 59: - if (state === 3) { + if (state === 3 || !previousWhitespace && state === 2) { comments.push(scanner.getTokenText()); break; } @@ -27942,6 +28013,7 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); @@ -28003,11 +28075,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); + var indentText = skipWhitespaceOrAsterisk(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -31024,14 +31096,14 @@ var ts; } if (ownConfig.extendedConfigPath) { resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -31147,7 +31219,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -31159,21 +31231,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -32743,14 +32801,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind", "bindSourceFile", { path: file.path }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind", "bindSourceFile", { path: file.path }, true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -34582,6 +34640,11 @@ var ts; node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 157: + if (currentFlow && parent.kind === 176) { + node.flowNode = currentFlow; + } + break; case 105: node.flowNode = currentFlow; break; @@ -35312,7 +35375,7 @@ var ts; } function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 || (instanceState === 2 && !!options.preserveConstEnums); + return instanceState === 1 || (instanceState === 2 && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1)) { @@ -36321,6 +36384,24 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432, name)); @@ -37034,6 +37115,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -37326,7 +37411,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -38688,7 +38773,8 @@ var ts; return { accessibility: 2, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -40655,14 +40741,15 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { newModifierFlags |= 1; } if (addingDeclare && !(newModifierFlags & 1) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { newModifierFlags |= 2; } @@ -40683,12 +40770,15 @@ var ts; var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; var oldFlags = context.flags; context.flags |= 8388608; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(undefined, undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -41761,7 +41851,7 @@ var ts; } if (ts.isParameter(declaration)) { var func = declaration.parent; - if (func.kind === 168 && !hasNonBindableDynamicName(func)) { + if (func.kind === 168 && hasBindableName(func)) { var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); @@ -42185,8 +42275,18 @@ var ts; } if (symbol.flags & 134217728) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } var declaration = symbol.valueDeclaration; @@ -43144,8 +43244,8 @@ var ts; var name = ts.getNameOfDeclaration(node); return !!name && isLateBindableName(name); } - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } function isNonBindableDynamicName(node) { return ts.isDynamicName(node) && !isLateBindableName(node); @@ -44213,12 +44313,22 @@ var ts; if (t.flags & 3145728) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 && baseTypes.length ? getIntersectionType(baseTypes) : @@ -44708,7 +44818,7 @@ var ts; } } if ((declaration.kind === 167 || declaration.kind === 168) && - !hasNonBindableDynamicName(declaration) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { var otherKind = declaration.kind === 167 ? 168 : 167; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); @@ -44905,7 +45015,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 167 && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; @@ -45122,6 +45232,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { @@ -45228,7 +45341,7 @@ var ts; } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); @@ -45781,7 +45894,14 @@ var ts; addElement(type, 8, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { addElement(isArrayLikeType(type) && getIndexTypeOfType(type, 1) || errorType, 4, (_b = target.labeledElementDeclarations) === null || _b === void 0 ? void 0 : _b[i]); @@ -45792,7 +45912,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } for (var i = 0; i < lastRequiredIndex; i++) { if (expandedFlags[i] & 2) @@ -45895,47 +46017,33 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types, primitivesOnly) { + function removeSubtypes(types, hasObjectTypes) { + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes", "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return false; + } + } + count++; + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1) || + !(ts.getObjectFlags(getTargetType(target)) & 1) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1) || - !(ts.getObjectFlags(getTargetType(target)) & 1) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } @@ -45947,10 +46055,12 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 && includes & 4 || - t.flags & 256 && includes & 8 || - t.flags & 2048 && includes & 64 || - t.flags & 8192 && includes & 4096 || + var flags = t.flags; + var remove = flags & 128 && includes & 4 || + flags & 256 && includes & 8 || + flags & 2048 && includes & 64 || + flags & 8192 && includes & 4096 || + flags & 32768 && includes & 16384 || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -46009,20 +46119,18 @@ var ts; if (includes & 3) { return includes & 1 ? includes & 8388608 ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1: - if (includes & (134220672 | 8192)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 && includes & 134217728) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2: - if (!removeSubtypes(typeSet, !(includes & 262144))) { - return errorType; - } - break; + if (unionReduction & (1 | 2)) { + if (includes & (2944 | 8192) || includes & 16384 && includes & 32768) { + removeRedundantLiteralTypes(typeSet, includes); + } + if (includes & 128 && includes & 134217728) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + } + if (unionReduction & 2) { + if (!removeSubtypes(typeSet, !!(includes & 524288))) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 ? includes & 4194304 ? nullType : nullWideningType : @@ -46107,7 +46215,7 @@ var ts; origin.flags & 1048576 ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 ? "&" + getTypeListId(origin.types) : "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -46299,7 +46407,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576) { @@ -46334,7 +46442,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes", "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -46384,11 +46492,15 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 | 4)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 | 8 | 131072)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } function maybeNonDistributiveNameType(type) { @@ -46519,7 +46631,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -46614,7 +46725,8 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } @@ -46647,7 +46759,7 @@ var ts; if (prop) { if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 107); @@ -46944,7 +47056,7 @@ var ts; if (objectType.flags & 3) { return objectType; } - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -47013,13 +47125,24 @@ var ts; } return type; } + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 179 + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 179 + && ts.length(root.node.extendsType.elements) === 1; + } + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -47031,10 +47154,10 @@ var ts; } combinedMapper = mergeTypeMappers(mapper, context.mapper); } - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { - if (!(inferredExtendsType.flags & 3) && (checkType.flags & 1 || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { - if (checkType.flags & 1) { + if (!(inferredExtendsType.flags & 3) && ((checkType.flags & 1 && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (checkType.flags & 1 && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } var falseType_1 = getTypeFromTypeNode(root.node.falseType); @@ -47055,8 +47178,8 @@ var ts; } result = createType(16777216); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; @@ -47387,11 +47510,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672) { + if (type.flags & 2944) { if (!type.freshType) { - var freshType = type.flags & 134217728 ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -47401,12 +47522,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 ? type.regularType : + return type.flags & 2944 ? type.regularType : type.flags & 1048576 ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672) && type.freshType === type; + return !!(type.flags & 2944) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; @@ -47749,15 +47870,15 @@ var ts; var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); var newAliasSymbol = aliasSymbol || type.aliasSymbol; - var id = getTypeListId(typeArguments) + (newAliasSymbol ? "@" + getSymbolId(newAliasSymbol) : ""); + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters) + (target.aliasSymbol ? "@" + getSymbolId(target.aliasSymbol) : ""), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); result = target.objectFlags & 4 ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); @@ -47892,7 +48013,7 @@ var ts; var root = type.root; if (root.outerTypeParameters) { var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); @@ -47921,7 +48042,7 @@ var ts; return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { - ts.tracing.instant("checkTypes", "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } @@ -48855,7 +48976,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes", "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -49219,7 +49340,7 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728) && (target.flags & 3145728)) { @@ -49334,9 +49455,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -49533,7 +49654,7 @@ var ts; }; } if (expandingFlags === 3) { - ts.tracing.instant("checkTypes", "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -49564,9 +49685,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes", "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes", "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -49765,20 +49886,17 @@ var ts; } } else if (source.flags & 134217728) { - if (target.flags & 134217728) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 | 4)) || !!isRelatedTo(t, target.types[i], false); })) { - return -1; - } + if (target.flags & 134217728 && + source.texts.length === target.texts.length && + source.types.length === target.types.length && + ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && + ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 | 4)) || !!isRelatedTo(t, target.types[i], false); })) { + return -1; } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + var constraint = getBaseConstraintOfType(source); + if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) { + resetErrorInfo(saveErrorInfo); + return result; } } else if (source.flags & 268435456) { @@ -49968,7 +50086,7 @@ var ts; var sourceProperty = sourcePropertiesFiltered_1[_i]; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { - ts.tracing.instant("checkTypes", "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0; } } @@ -50001,8 +50119,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -50015,9 +50133,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } var result = -1; for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) { @@ -50649,7 +50767,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes", "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes", "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); cache.variances = ts.emptyArray; variances = []; var _loop_19 = function (tp) { @@ -50680,7 +50798,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -51002,7 +51120,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 ? stringType : + type.flags & 128 ? stringType : type.flags & 256 ? numberType : type.flags & 2048 ? bigintType : type.flags & 512 ? booleanType : @@ -51011,7 +51129,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 && isFreshLiteralType(type) ? stringType : + type.flags & 128 && isFreshLiteralType(type) ? stringType : type.flags & 256 && isFreshLiteralType(type) ? numberType : type.flags & 2048 && isFreshLiteralType(type) ? bigintType : type.flags & 512 && isFreshLiteralType(type) ? booleanType : @@ -52264,7 +52382,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 && s.flags & 134217856 || t.flags & 8 && s.flags & 256); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 && s.flags & 128 || t.flags & 8 && s.flags & 256); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 && t.flags & 524288 && s.symbol && s.symbol === t.symbol || @@ -52465,6 +52583,10 @@ var ts; return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); + case 157: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); case 216: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 && isMatchingReference(source.right, target)); } @@ -52864,7 +52986,22 @@ var ts; if (type.flags & 1048576) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576) { + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, undefined, undefined, newOrigin); } return type.flags & 131072 || f(type) ? type : neverType; } @@ -53228,7 +53365,7 @@ var ts; } function getTypeAtFlowNode(flow) { if (flowDepth === 2000) { - ts.tracing.instant("checkTypes", "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -53584,10 +53721,13 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var includesNullable = strictNullChecks && maybeTypeOfKind(type, 98304); + var removeNullable = includesNullable && ts.isOptionalChain(access); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); @@ -53937,7 +54077,10 @@ var ts; return assignableType; } } - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -54095,7 +54238,9 @@ var ts; if (isNonLocalAlias(symbol, 111551) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -54128,7 +54273,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; if (localOrExportSymbol.flags & 32) { @@ -55005,7 +55150,7 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { var symbolName_3 = getSymbolOfNode(element).escapedName; var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); if (propertyType) { @@ -55185,6 +55330,8 @@ var ts; var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } + case 225: + return getContextualType(parent, contextFlags); case 283: return getContextualTypeForJsxExpression(parent); case 280: @@ -55265,14 +55412,17 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -56385,7 +56535,7 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -56419,7 +56569,7 @@ var ts; } else { if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 107); @@ -56435,8 +56585,7 @@ var ts; } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 || + if (assignmentKind === 1 || prop && !(prop.flags & (3 | 4 | 98304)) && !(prop.flags & 8192 && propType.flags & 1048576)) { return propType; } @@ -56444,7 +56593,7 @@ var ts; return getFlowTypeOfProperty(node, prop); } var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); @@ -57014,6 +57163,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -57047,8 +57205,7 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; @@ -57234,19 +57391,7 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType && thisType !== voidType && node.kind !== 204) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -58394,7 +58539,7 @@ var ts; if (returnType.flags & 12288 && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 && node.parent.kind === 233 && + if (node.kind === 203 && !node.questionDotToken && node.parent.kind === 233 && returnType.flags & 16384 && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -58417,7 +58562,8 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { @@ -60279,7 +60425,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType; } function getContextNode(node) { if (node.kind === 281 && !ts.isJsxSelfClosingElement(node.parent)) { @@ -60295,7 +60441,7 @@ var ts; context.contextualType = contextualType; context.inferenceContext = inferenceContext; var type = checkExpression(node, checkMode | 1 | (inferenceContext ? 2 : 0)); - var result = maybeTypeOfKind(type, 134220672) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -60370,13 +60516,13 @@ var ts; } if (contextualType.flags & 58982400) { var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 134217856) || + return maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 128) || maybeTypeOfKind(constraint, 8) && maybeTypeOfKind(candidateType, 256) || maybeTypeOfKind(constraint, 64) && maybeTypeOfKind(candidateType, 2048) || maybeTypeOfKind(constraint, 4096) && maybeTypeOfKind(candidateType, 8192) || isLiteralOfContextualType(candidateType, constraint); } - return !!(contextualType.flags & (134217856 | 4194304 | 268435456) && maybeTypeOfKind(candidateType, 134217856) || + return !!(contextualType.flags & (128 | 4194304 | 134217728 | 268435456) && maybeTypeOfKind(candidateType, 128) || contextualType.flags & 256 && maybeTypeOfKind(candidateType, 256) || contextualType.flags & 2048 && maybeTypeOfKind(candidateType, 2048) || contextualType.flags & 512 && maybeTypeOfKind(candidateType, 512) || @@ -60586,7 +60732,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check", "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check", "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -60596,7 +60742,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -61176,7 +61322,7 @@ var ts; if (ts.isPrivateIdentifier(node.name)) { error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { var otherKind = node.kind === 167 ? 168 : 167; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { @@ -61256,7 +61402,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728); })) { - errorOrSuggestion(false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 && symbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -62126,7 +62272,7 @@ var ts; if (node.name && node.name.kind === 158) { checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072); }); @@ -62306,11 +62452,11 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -62725,10 +62871,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check", "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check", "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -63561,7 +63707,7 @@ var ts; if (ts.getObjectFlags(type) & 1 && ts.isClassLike(classDeclaration)) { for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!ts.hasSyntacticModifier(member, 32) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0); @@ -64395,7 +64541,7 @@ var ts; if (symbol.flags & 512 && !inAmbientContext && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -64556,7 +64702,7 @@ var ts; error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728); })) { - errorOrSuggestion(false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -65099,7 +65245,7 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check", "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check", "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -65132,15 +65278,15 @@ var ts; break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check", "checkSourceFile", { path: node.path }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check", "checkSourceFile", { path: node.path }, true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -65927,7 +66073,7 @@ var ts; return true; } return !!(target.flags & 111551) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -65935,13 +66081,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; if (target && ts.getEffectiveModifierFlags(node) & 1 && target.flags & 111551 && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { return true; } } @@ -66160,8 +66307,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -67243,18 +67389,30 @@ var ts; return true; } if (forInOrOfStatement.kind === 239 && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768) === 0) { + if (!(forInOrOfStatement.flags & 32768)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 166) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } @@ -70882,8 +71040,7 @@ var ts; } function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } function visitEnumDeclaration(node) { if (!shouldEmitEnumDeclaration(node)) { @@ -70959,7 +71116,7 @@ var ts; if (!node) { return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } function hasNamespaceQualifiedExportName(node) { return isExportOfNamespace(node) @@ -71594,6 +71751,9 @@ var ts; function visitCallExpression(node) { if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), undefined, undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } return ts.visitEachChild(node, visitor, context); @@ -78612,7 +78772,7 @@ var ts; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { var exportName = exportedNames_3[_i]; noSubstitution[ts.getNodeId(expression)] = true; - expression = createExportExpression(exportName, expression); + expression = factory.createParenthesizedExpression(createExportExpression(exportName, expression)); } return expression; } @@ -79634,7 +79794,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -79732,7 +79893,7 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { @@ -80007,11 +80168,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -80083,6 +80246,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -80147,8 +80311,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -80172,8 +80336,8 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { @@ -80186,12 +80350,12 @@ var ts; } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; @@ -80811,7 +80975,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133)] : [], factory.createVariableDeclarationList([varDecl], 2)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -80952,6 +81118,8 @@ var ts; } } case 252: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -81045,6 +81213,8 @@ var ts; if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -81384,9 +81554,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit", "transformNodes", node.kind === 297 ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "transformNodes", node.kind === 297 ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } state = 2; ts.performance.mark("afterTransform"); @@ -81892,15 +82062,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit", "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit", "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit", "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -86811,7 +86981,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); - lineContent = lineContent.replace("\t", " "); + lineContent = lineContent.replace(/\t/g, " "); context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; @@ -87098,7 +87268,7 @@ var ts; var currentNodeModulesDepth = 0; var modulesWithElidedImports = new ts.Map(); var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program", "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -87158,13 +87328,13 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program", "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); var structureIsReused; - ts.tracing.push("program", "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -87202,19 +87372,19 @@ var ts; }); } } - ts.tracing.push("program", "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, false, false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program", "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "processTypeReferences", { count: typeReferences.length }); var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } if (rootNames.length && !skipDefaultLib) { var defaultLibraryFileName = getDefaultLibraryFileName(); @@ -87326,19 +87496,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program", "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -87346,12 +87516,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program", "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -87727,12 +87897,12 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit", "emitBuildInfo", {}, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emitBuildInfo", {}, true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), undefined, ts.noTransformers, false, true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -87776,9 +87946,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit", "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -88362,13 +88532,13 @@ var ts; return redirect; } function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program", "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -88593,9 +88763,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program", "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); @@ -88877,6 +89047,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -89369,7 +89542,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) return; @@ -89384,7 +89557,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -90778,6 +90951,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -91465,12 +91639,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -91484,40 +91654,44 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); + var result_15 = ts.forEach(targets, function (p) { return !ts.containsIgnoredPath(p) && cb(p, referenceRedirect === p); }); if (result_15) return result_15; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) return undefined; + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); var result_16 = cb(option, target === referenceRedirect); if (result_16) return result_16; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; function getAllModulePaths(importingFileName, importedFileName, host) { @@ -91555,9 +91729,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + var state_8 = _loop_24(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_8 === "break") break; } if (allFileNames.size) { @@ -94556,7 +94730,7 @@ var ts; updateSolutionBuilderHost(sys, cb, buildHost); var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions); var exitStatus = buildOptions.clean ? builder.clean() : builder.build(); - ts.tracing.dumpLegend(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.dumpLegend(); return sys.exit(exitStatus); } function createReportErrorSummary(sys, options) { @@ -94667,16 +94841,16 @@ var ts; } function enableStatisticsAndTracing(system, compilerOptions, isBuildMode) { if (canReportDiagnostics(system, compilerOptions)) { - ts.performance.enable(); + ts.performance.enable(system); } if (canTrace(system, compilerOptions)) { - ts.tracing.startTracing(isBuildMode ? 1 : 0, compilerOptions.generateTrace, compilerOptions.configFilePath); + ts.startTracing(isBuildMode ? 1 : 0, compilerOptions.generateTrace, compilerOptions.configFilePath); } } function reportStatistics(sys, program) { var compilerOptions = program.getCompilerOptions(); if (canTrace(sys, compilerOptions)) { - ts.tracing.stopTracing(program.getTypeCatalog()); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.stopTracing(program.getTypeCatalog()); } var statistics; if (canReportDiagnostics(sys, compilerOptions)) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 2b79c7e22f1fb..78378cc6eb926 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -3211,16 +3211,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3228,27 +3234,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); } - }, - PerformanceObserver: PerformanceObserver_1 + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); + } + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3279,7 +3284,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3310,6 +3314,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3318,7 +3325,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3331,7 +3344,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3365,40 +3385,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3442,39 +3463,41 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { + // enable the above using startTracing() +})(ts || (ts = {})); +// `tracingEnabled` should never be used directly, only through the above +/* @internal */ +(function (ts) { + var tracingEnabled; + (function (tracingEnabled) { var Mode; (function (Mode) { Mode[Mode["Project"] = 0] = "Project"; Mode[Mode["Build"] = 1] = "Build"; Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + })(Mode = tracingEnabled.Mode || (tracingEnabled.Mode = {})); var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); @@ -3483,9 +3506,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount + : mode === 2 /* Server */ ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3494,24 +3517,21 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; + ts.tracing = undefined; if (typeCatalog) { dumpTypes(typeCatalog); } @@ -3521,11 +3541,7 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; - } - tracing.isTracing = isTracing; + tracingEnabled.stopTracing = stopTracing; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3535,13 +3551,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3551,45 +3565,40 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) return; @@ -3611,7 +3620,6 @@ var ts; } function dumpTypes(types) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3691,11 +3699,15 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled = ts.tracingEnabled || (ts.tracingEnabled = {})); +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + // define after tracingEnabled is initialized + ts.startTracing = ts.tracingEnabled.startTracing; })(ts || (ts = {})); var ts; (function (ts) { @@ -4690,10 +4702,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -6124,7 +6132,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -7092,6 +7100,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7341,7 +7350,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7651,7 +7660,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -7912,6 +7921,8 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8381,6 +8392,9 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8453,6 +8467,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8525,6 +8540,7 @@ var ts; The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8793,8 +8809,9 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -9924,6 +9941,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -10926,15 +10944,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -10951,6 +10963,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11704,19 +11741,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11727,7 +11767,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -15587,6 +15627,8 @@ var ts; return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; case 203 /* CallExpression */: return node.arguments[0]; + case 256 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -17150,11 +17192,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -17839,6 +17890,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -18540,7 +18597,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -18884,6 +18941,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -18946,19 +19007,33 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + } }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); + var cache = createSymlinkCache(cwd, getCanonicalFileName); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; @@ -18968,15 +19043,15 @@ var ts; var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19360,6 +19435,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -19840,6 +19923,10 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; })(ts || (ts = {})); /* @internal */ var ts; @@ -28442,62 +28529,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 157 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28510,7 +28593,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -29386,8 +29469,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29399,6 +29482,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -34533,6 +34621,7 @@ var ts; function parseTagComments(indent, initialMargin) { var comments = []; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34558,7 +34647,8 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace comments.push(scanner.getTokenText()); break; } @@ -34615,6 +34705,7 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); @@ -34679,11 +34770,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); + var indentText = skipWhitespaceOrAsterisk(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -38107,14 +38198,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38234,7 +38325,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38246,22 +38337,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -40184,14 +40260,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -42350,6 +42426,11 @@ var ts; node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 157 /* QualifiedName */: + if (currentFlow && parent.kind === 176 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; @@ -43177,7 +43258,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -44459,6 +44540,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -45334,6 +45434,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45657,7 +45761,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -47247,7 +47351,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -49045,7 +49150,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49433,15 +49538,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49463,12 +49569,15 @@ var ts; var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -50805,7 +50914,7 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + if (func.kind === 168 /* SetAccessor */ && hasBindableName(func)) { var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); @@ -51301,8 +51410,18 @@ var ts; } if (symbol.flags & 134217728 /* ModuleExports */) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables @@ -52380,10 +52499,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -53624,12 +53743,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -54196,7 +54325,7 @@ var ts; } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); @@ -54405,7 +54534,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 167 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; @@ -54652,6 +54781,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54769,7 +54901,7 @@ var ts; } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); @@ -55371,8 +55503,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55385,7 +55524,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55496,52 +55637,40 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types, primitivesOnly) { + function removeSubtypes(types, hasObjectTypes) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return false; + } + } + count++; + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } @@ -55553,10 +55682,12 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55622,20 +55753,18 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (unionReduction & (1 /* Literal */ | 2 /* Subtype */)) { + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + } + if (unionReduction & 2 /* Subtype */) { + if (!removeSubtypes(typeSet, !!(includes & 524288 /* Object */))) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55725,7 +55854,7 @@ var ts; origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -55957,7 +56086,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -56000,7 +56129,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56050,11 +56179,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56190,7 +56325,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56294,7 +56428,8 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } @@ -56328,7 +56463,7 @@ var ts; if (prop) { if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); @@ -56662,7 +56797,7 @@ var ts; return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56738,6 +56873,21 @@ var ts; } return type; } + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 179 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 179 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; @@ -56745,9 +56895,10 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56763,16 +56914,16 @@ var ts; combinedMapper = mergeTypeMappers(mapper, context.mapper); } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56801,8 +56952,8 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; @@ -57150,11 +57301,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57164,12 +57313,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57551,15 +57700,15 @@ var ts; var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); var newAliasSymbol = aliasSymbol || type.aliasSymbol; - var id = getTypeListId(typeArguments) + (newAliasSymbol ? "@" + getSymbolId(newAliasSymbol) : ""); + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters) + (target.aliasSymbol ? "@" + getSymbolId(target.aliasSymbol) : ""), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); @@ -57717,7 +57866,7 @@ var ts; // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); @@ -57752,7 +57901,7 @@ var ts; // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing // with a combination of infinite generic types that perpetually generate new type identities. We stop // the recursion here by yielding the error type. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } @@ -58788,7 +58937,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -59239,7 +59388,7 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { @@ -59365,9 +59514,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59596,7 +59745,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59631,9 +59780,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -59876,20 +60025,17 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } + if (target.flags & 134217728 /* TemplateLiteral */ && + source.texts.length === target.texts.length && + source.types.length === target.types.length && + ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && + ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { + return -1 /* True */; } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + var constraint = getBaseConstraintOfType(source); + if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) { + resetErrorInfo(saveErrorInfo); + return result; } } else if (source.flags & 268435456 /* StringMapping */) { @@ -60148,7 +60294,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60187,8 +60333,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60201,9 +60347,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -60903,7 +61049,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -60942,7 +61088,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -61326,7 +61472,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61335,7 +61481,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -62777,7 +62923,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -63006,6 +63152,10 @@ var ts; return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); + case 157 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); case 216 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } @@ -63418,7 +63568,27 @@ var ts; if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -63819,7 +63989,7 @@ var ts; if (flowDepth === 2000) { // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -64243,10 +64413,13 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var includesNullable = strictNullChecks && maybeTypeOfKind(type, 98304 /* Nullable */); + var removeNullable = includesNullable && ts.isOptionalChain(access); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); @@ -64669,10 +64842,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -64849,7 +65027,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -64890,7 +65073,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; if (localOrExportSymbol.flags & 32 /* Class */) { @@ -65948,7 +66131,7 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. @@ -66177,6 +66360,8 @@ var ts; var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } + case 225 /* NonNullExpression */: + return getContextualType(parent, contextFlags); case 283 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); case 280 /* JsxAttribute */: @@ -66263,16 +66448,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -67609,7 +67797,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67643,7 +67835,7 @@ var ts; } else { if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); @@ -67662,8 +67854,7 @@ var ts; // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || + if (assignmentKind === 1 /* Definite */ || prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } @@ -67675,7 +67866,7 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); @@ -68323,6 +68514,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68375,8 +68575,7 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; @@ -68580,19 +68779,7 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -69961,7 +70148,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 203 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 233 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -69984,7 +70171,8 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { @@ -72069,7 +72257,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType; } function getContextNode(node) { if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { @@ -72088,7 +72276,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72172,7 +72360,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72180,7 +72368,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72433,7 +72621,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72443,7 +72631,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -73095,7 +73283,7 @@ var ts; if (ts.isPrivateIdentifier(node.name)) { error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; @@ -73179,7 +73367,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -74268,7 +74456,7 @@ var ts; // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74473,11 +74661,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -74961,10 +75153,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -76061,7 +76253,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -76987,7 +77179,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -77179,7 +77371,7 @@ var ts; error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77771,7 +77963,7 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -77807,15 +77999,15 @@ var ts; break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -78734,7 +78926,7 @@ var ts; // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true return !!(target.flags & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78742,13 +78934,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -78987,8 +79180,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -80138,19 +80330,31 @@ var ts; return true; } if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 166 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } @@ -84871,8 +85075,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -85006,7 +85209,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -85943,6 +86146,11 @@ var ts; if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } @@ -96166,7 +96374,7 @@ var ts; var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; - expression = createExportExpression(exportName, expression); + expression = factory.createParenthesizedExpression(createExportExpression(exportName, expression)); } return expression; } @@ -97818,7 +98026,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -97916,7 +98125,7 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { @@ -98209,11 +98418,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98296,6 +98507,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98365,8 +98577,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98390,8 +98602,8 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { @@ -98404,12 +98616,12 @@ var ts; } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; @@ -99106,7 +99318,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99275,6 +99489,8 @@ var ts; } } case 252 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99385,6 +99601,8 @@ var ts; if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99766,9 +99984,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -100364,15 +100582,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -105775,7 +105993,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -106109,7 +106327,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106185,15 +106403,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106231,13 +106449,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106245,7 +106463,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106368,19 +106586,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106388,12 +106606,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -106865,7 +107083,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -106874,7 +107092,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -106920,9 +107138,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107583,13 +107801,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -107848,9 +108066,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -108156,6 +108374,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108685,7 +108906,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108702,7 +108923,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -110431,6 +110652,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -111234,12 +111456,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111253,40 +111471,47 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_15 = ts.forEach(targets, function (p) { return !ts.containsIgnoredPath(p) && cb(p, referenceRedirect === p); }); if (result_15) return result_15; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); var result_16 = cb(option, target === referenceRedirect); if (result_16) return result_16; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111331,9 +111556,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + var state_8 = _loop_24(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_8 === "break") break; } if (allFileNames.size) { @@ -116935,7 +117160,7 @@ var ts; // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = getQuotePreference(sourceFile, preferences); var quoted = JSON.stringify(text); - return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'" : quoted; + return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted; } ts.quote = quote; function isEqualityOperatorKind(kind) { @@ -117302,9 +117527,9 @@ var ts; } ts.firstOrOnly = firstOrOnly; function getNameForExportedSymbol(symbol, scriptTarget) { - if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { + if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); } return symbol.name; @@ -119819,6 +120044,7 @@ var ts; } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) { var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -120306,7 +120532,7 @@ var ts; keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } @@ -120420,13 +120646,34 @@ var ts; ? 6 /* TypeAssertionKeywords */ : 7 /* TypeKeywords */; } + var variableDeclaration = getVariableDeclaration(location); ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { return true; } - symbol = ts.skipAlias(symbol, typeChecker); + // Filter out variables from their own initializers + // `const a = /* no 'a' here */` + if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { + return false; + } + // External modules can have global export declarations that will be + // available as global keywords in all scopes. But if the external module + // already has an explicit export and user only wants to user explicit + // module imports then the global keywords will be filtered out so auto + // import suggestions will win in the completion + var symbolOrigin = ts.skipAlias(symbol, typeChecker); + // We only want to filter out the global keywords + // Auto Imports are not available for scripts so this conditional is always false + if (!!sourceFile.externalModuleIndicator + && !compilerOptions.allowUmdGlobalAccess + && symbolToSortTextMap[ts.getSymbolId(symbol)] === SortText.GlobalsOrKeywords + && symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions) { + return false; + } + // Continue with origin symbol + symbol = symbolOrigin; // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); @@ -120440,6 +120687,18 @@ var ts; return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); }); } + function getVariableDeclaration(property) { + var variableDeclaration = ts.findAncestor(property, function (node) { + return ts.isFunctionBlock(node) || isArrowFunctionBody(node) || ts.isBindingPattern(node) + ? "quit" + : ts.isVariableDeclaration(node); + }); + return variableDeclaration; + } + function isArrowFunctionBody(node) { + return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node; + } + ; function isTypeOnlyCompletion() { return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && @@ -120699,18 +120958,19 @@ var ts; } return false; } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + function isNewIdentifierDefinitionLocation() { + if (contextToken) { + var containingNodeKind = contextToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { + switch (keywordForNode(contextToken)) { case 27 /* CommaToken */: return containingNodeKind === 203 /* CallExpression */ // func( a, | || containingNodeKind === 166 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ || containingNodeKind === 204 /* NewExpression */ // new C(a, | || containingNodeKind === 199 /* ArrayLiteralExpression */ // [a, | || containingNodeKind === 216 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 174 /* FunctionType */; // var x: (s: string, list| + || containingNodeKind === 174 /* FunctionType */ // var x: (s: string, list| + || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { x, | case 20 /* OpenParenToken */: return containingNodeKind === 203 /* CallExpression */ // func( | || containingNodeKind === 166 /* Constructor */ // constructor( | @@ -120727,7 +120987,8 @@ var ts; case 24 /* DotToken */: return containingNodeKind === 256 /* ModuleDeclaration */; // module A.| case 18 /* OpenBraceToken */: - return containingNodeKind === 252 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 252 /* ClassDeclaration */ // class A { | + || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { | case 62 /* EqualsToken */: return containingNodeKind === 249 /* VariableDeclaration */ // const x = a| || containingNodeKind === 216 /* BinaryExpression */; // x = a| @@ -126113,7 +126374,7 @@ var ts; * @param position The (character-indexed) position in the file where the check should * be performed. */ - function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { @@ -126125,7 +126386,7 @@ var ts; if (!existingDocComment && tokenStart < position) { return undefined; } - var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); if (!commentOwnerInfo) { return undefined; } @@ -126175,10 +126436,10 @@ var ts; function returnsDocComment(indentationStr, newLine) { return indentationStr + " * @returns" + newLine; } - function getCommentOwnerInfo(tokenAtPos) { - return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + function getCommentOwnerInfo(tokenAtPos, options) { + return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); }); } - function getCommentOwnerInfoWorker(commentOwner) { + function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { case 251 /* FunctionDeclaration */: case 208 /* FunctionExpression */: @@ -126187,9 +126448,9 @@ var ts; case 164 /* MethodSignature */: case 209 /* ArrowFunction */: var host = commentOwner; - return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host) }; + return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; case 288 /* PropertyAssignment */: - return getCommentOwnerInfoWorker(commentOwner.initializer); + return getCommentOwnerInfoWorker(commentOwner.initializer, options); case 252 /* ClassDeclaration */: case 253 /* InterfaceDeclaration */: case 162 /* PropertySignature */: @@ -126204,7 +126465,7 @@ var ts; ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1) } + ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } : { commentOwner: commentOwner }; } case 297 /* SourceFile */: @@ -126215,26 +126476,27 @@ var ts; // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. return commentOwner.parent.kind === 256 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 233 /* ExpressionStatement */: - return getCommentOwnerInfoWorker(commentOwner.expression); + return getCommentOwnerInfoWorker(commentOwner.expression, options); case 216 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } return ts.isFunctionLike(be.right) - ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right) } + ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner: commentOwner }; } case 163 /* PropertyDeclaration */: var init = commentOwner.initializer; if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { - return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init) }; + return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; } } } - function hasReturn(node) { - return ts.isArrowFunction(node) && ts.isExpression(node.body) - || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; }); + function hasReturn(node, options) { + return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && + (ts.isArrowFunction(node) && ts.isExpression(node.body) + || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { while (rightHandSide.kind === 207 /* ParenthesizedExpression */) { @@ -126532,6 +126794,16 @@ var ts; addChildrenRecursively(child); endNode(); } + function addNodeWithRecursiveInitializer(node) { + if (node.initializer && isFunctionOrClassExpression(node.initializer)) { + startNode(node); + ts.forEachChild(node.initializer, addChildrenRecursively); + endNode(); + } + else { + addNodeWithRecursiveChild(node, node.initializer); + } + } /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node) { var _a; @@ -126561,6 +126833,10 @@ var ts; } break; case 163 /* PropertyDeclaration */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveInitializer(node); + } + break; case 162 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); @@ -126599,21 +126875,16 @@ var ts; break; case 198 /* BindingElement */: case 288 /* PropertyAssignment */: - case 249 /* VariableDeclaration */: - var _e = node, name = _e.name, initializer = _e.initializer; - if (ts.isBindingPattern(name)) { - addChildrenRecursively(name); - } - else if (initializer && isFunctionOrClassExpression(initializer)) { - // Add a node for the VariableDeclaration, but not for the initializer. - startNode(node); - ts.forEachChild(initializer, addChildrenRecursively); - endNode(); + case 249 /* VariableDeclaration */: { + var child = node; + if (ts.isBindingPattern(child.name)) { + addChildrenRecursively(child.name); } else { - addNodeWithRecursiveChild(node, initializer); + addNodeWithRecursiveInitializer(child); } break; + } case 251 /* FunctionDeclaration */: var nameNode = node.name; // If we see a function declaration track as a possible ES5 class @@ -126628,8 +126899,8 @@ var ts; break; case 255 /* EnumDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } @@ -126640,8 +126911,8 @@ var ts; case 221 /* ClassExpression */: case 253 /* InterfaceDeclaration */: startNode(node); - for (var _h = 0, _j = node.members; _h < _j.length; _h++) { - var member = _j[_h]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); @@ -126724,7 +126995,7 @@ var ts; defineCall.arguments[0] : defineCall.arguments[0].expression; var memberName = defineCall.arguments[1]; - var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1]; + var _j = startNestedNodes(node, className), depth = _j[0], classNameIdentifier = _j[1]; startNode(node, classNameIdentifier); startNode(node, ts.setTextRange(ts.factory.createIdentifier(memberName.text), memberName)); addChildrenRecursively(node.arguments[2]); @@ -129656,7 +129927,19 @@ var ts; itemsSeen += item.length; } ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. - return { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var help = { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var selected = help.items[selectedItemIndex]; + if (selected.isVariadic) { + var firstRest = ts.findIndex(selected.parameters, function (p) { return !!p.isRest; }); + if (-1 < firstRest && firstRest < selected.parameters.length - 1) { + // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL + help.argumentIndex = selected.parameters.length; + } + else { + help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1); + } + } + return help; } function createTypeHelpItems(symbol, _a, sourceFile, checker) { var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; @@ -129738,14 +130021,15 @@ var ts; printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); - return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + var isRest = !!(parameter.checkFlags & 32768 /* RestParameter */); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional, isRest: isRest }; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false, isRest: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -130008,7 +130292,7 @@ var ts; return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && - hasReturnStatementWithPromiseHandler(node.body) && + hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker); } function returnsPromise(node, checker) { @@ -130020,23 +130304,23 @@ var ts; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - function hasReturnStatementWithPromiseHandler(body) { - return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + function hasReturnStatementWithPromiseHandler(body, checker) { + return !!ts.forEachReturnStatement(body, function (statement) { return isReturnStatementWithFixablePromiseHandler(statement, checker); }); } - function isReturnStatementWithFixablePromiseHandler(node) { - return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + function isReturnStatementWithFixablePromiseHandler(node, checker) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - function isFixablePromiseHandler(node) { + function isFixablePromiseHandler(node, checker) { // ensure outermost call exists and is a promise handler - if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + if (!isPromiseHandler(node) || !node.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } // ensure all chained calls are valid var currentNode = node.expression; while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { - if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } currentNode = currentNode.expression; @@ -130059,7 +130343,7 @@ var ts; }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts - function isFixablePromiseArgument(arg) { + function isFixablePromiseArgument(arg, checker) { switch (arg.kind) { case 251 /* FunctionDeclaration */: case 208 /* FunctionExpression */: @@ -130067,8 +130351,16 @@ var ts; visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); // falls through case 103 /* NullKeyword */: - case 78 /* Identifier */: // identifier includes undefined return true; + case 78 /* Identifier */: + case 201 /* PropertyAccessExpression */: { + var symbol = checker.getSymbolAtLocation(arg); + if (!symbol) { + return false; + } + return checker.isUndefinedSymbol(symbol) || + ts.some(ts.skipAlias(symbol, checker).declarations, function (d) { return ts.isFunctionLike(d) || ts.hasInitializer(d) && !!d.initializer && ts.isFunctionLike(d.initializer); }); + } default: return false; } @@ -132409,14 +132701,17 @@ var ts; processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } if (!formattingScanner.isOnToken()) { + var indentation = formatting.SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false) + ? initialIndentation + options.indentSize + : initialIndentation; var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); - if (options.trimTrailingWhitespace !== false) { - trimTrailingWhitespacesForRemainingRange(); - } + indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); } } + if (options.trimTrailingWhitespace !== false) { + trimTrailingWhitespacesForRemainingRange(); + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -132463,10 +132758,9 @@ var ts; // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; } - else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; - } - else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { @@ -132554,6 +132848,7 @@ var ts; case 275 /* JsxOpeningElement */: case 276 /* JsxClosingElement */: case 274 /* JsxSelfClosingElement */: + case 223 /* ExpressionWithTypeArguments */: return false; } break; @@ -133355,6 +133650,7 @@ var ts; } SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var _a; var parent = current.parent; // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if // * parent and child nodes start on the same line, or @@ -133370,7 +133666,25 @@ var ts; childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + var firstListChild = (_a = getContainingList(current, sourceFile)) === null || _a === void 0 ? void 0 : _a[0]; + // A list indents its children if the children begin on a later line than the list itself: + // + // f1( L0 - List start + // { L1 - First child start: indented, along with all other children + // prop: 0 + // }, + // { + // prop: 1 + // } + // ) + // + // f2({ L0 - List start and first child start: children are not indented. + // prop: 0 Object properties are indented only one level, because the list + // }, { itself contributes nothing. + // prop: 1 L3 - The indentation of the second object literal is best understood by + // }) looking at the relationship between the list and *first* list item. + var listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line; + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -133483,6 +133797,49 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + // A multiline conditional typically increases the indentation of its whenTrue and whenFalse children: + // + // condition + // ? whenTrue + // : whenFalse; + // + // However, that indentation does not apply if the subexpressions themselves span multiple lines, + // applying their own indentation: + // + // (() => { + // return complexCalculationForCondition(); + // })() ? { + // whenTrue: 'multiline object literal' + // } : ( + // whenFalse('multiline parenthesized expression') + // ); + // + // In these cases, we must discard the indentation increase that would otherwise be applied to the + // whenTrue and whenFalse children to avoid double-indenting their contents. To identify this scenario, + // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse + // branch beginning on the line that the whenTrue branch ends. + function childIsUnindentedBranchOfConditionalExpression(parent, child, childStartLine, sourceFile) { + if (ts.isConditionalExpression(parent) && (child === parent.whenTrue || child === parent.whenFalse)) { + var conditionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.condition.end).line; + if (child === parent.whenTrue) { + return childStartLine === conditionEndLine; + } + else { + // On the whenFalse side, we have to look at the whenTrue side, because if that one was + // indented, whenFalse must also be indented: + // + // const y = true + // ? 1 : ( L1: whenTrue indented because it's on a new line + // 0 L2: indented two stops, one because whenTrue was indented + // ); and one because of the parentheses spanning multiple lines + var trueStartLine = getStartLineAndCharacterForNode(parent.whenTrue, sourceFile).line; + var trueEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.whenTrue.end).line; + return conditionEndLine === trueStartLine && trueEndLine === childStartLine; + } + } + return false; + } + SmartIndenter.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) { if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) @@ -133728,7 +134085,7 @@ var ts; if (childKind === 177 /* TypeLiteral */ || childKind === 179 /* TupleType */) { return false; } - // falls through + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -135211,7 +135568,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + errorCodes: [ + ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], getCodeActions: function (context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { @@ -136223,7 +136583,7 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); - var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; @@ -136249,10 +136609,10 @@ var ts; _loop_12(returnStatement); } } - function getReturnStatementsWithPromiseHandlers(body) { + function getReturnStatementsWithPromiseHandlers(body, checker) { var res = []; ts.forEachReturnStatement(body, function (ret) { - if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + if (ts.isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; @@ -136501,6 +136861,7 @@ var ts; case 103 /* NullKeyword */: // do not produce a transformed statement for a null argument break; + case 201 /* PropertyAccessExpression */: case 78 /* Identifier */: // identifier includes undefined if (!argName) { // undefined was argument passed to promise handler @@ -136534,7 +136895,7 @@ var ts; var statement = _f[_i]; if (ts.isReturnStatement(statement)) { seenReturnStatement = true; - if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + if (ts.isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -136551,7 +136912,7 @@ var ts; : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); } else { - var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; + var innerRetStmts = ts.isFixablePromiseHandler(funcBody, transformer.checker) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return innerCbBody; @@ -136644,6 +137005,9 @@ var ts; else if (ts.isIdentifier(funcNode)) { name = getMapEntryOrDefault(funcNode); } + else if (ts.isPropertyAccessExpression(funcNode) && ts.isIdentifier(funcNode.name)) { + name = getMapEntryOrDefault(funcNode.name); + } // return undefined argName when arg is null or undefined // eslint-disable-next-line no-in-operator if (!name || "identifier" in name && name.identifier.text === "undefined") { @@ -137634,7 +137998,7 @@ var ts; : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; + var moduleSpecifier = getBestFix(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences), sourceFile, program, host).moduleSpecifier; var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } @@ -137642,7 +138006,7 @@ var ts; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); + return getBestFix(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, program, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -137821,8 +138185,7 @@ var ts; function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); - var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + return ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences) .map(function (moduleSpecifier) { @@ -137832,18 +138195,6 @@ var ts; : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; }); }); - // Sort by presence in package.json, then shortest paths first - return ts.sort(choicesForEachExportingModule, function (a, b) { - var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier); - var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier); - if (allowsImportingA && !allowsImportingB) { - return -1; - } - if (allowsImportingB && !allowsImportingA) { - return 1; - } - return a.moduleSpecifier.length - b.moduleSpecifier.length; - }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); @@ -137864,7 +138215,28 @@ var ts; var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, context.host) }); + } + function sortFixes(fixes, sourceFile, program, host) { + var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier); }); + } + function getBestFix(fixes, sourceFile, program, host) { + // These will always be placed first if available, and are better than other kinds + if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { + return fixes[0]; + } + var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; + return fixes.reduce(function (best, fix) { + return compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + }); + } + function compareModuleSpecifiers(a, b, allowsImportingSpecifier) { + if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { + return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + } + return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; @@ -137971,7 +138343,7 @@ var ts; if (!exported) return undefined; var symbol = exported.symbol, kind = exported.kind; - var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + var info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); return info && __assign({ symbol: symbol, kind: kind }, info); } function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) { @@ -138006,7 +138378,7 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -138020,21 +138392,20 @@ var ts; // but we can still offer completions for it. // - `aliased.parent` will be undefined if the module is exporting `globalThis.something`, // or another expression that resolves to a global. - return getDefaultExportInfoWorker(aliased, aliased.parent, checker, compilerOptions); + return getDefaultExportInfoWorker(aliased, checker, compilerOptions); } } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + return { symbolForMeaning: defaultExport, name: ts.getNameForExportedSymbol(defaultExport, compilerOptions.target) }; } function getNameForExportDefault(symbol) { return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + var _a; if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.text; - } + return (_a = ts.tryCast(ts.skipOuterExpressions(declaration.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export"); @@ -139531,7 +139902,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + errorCodes: [ + ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ], getCodeActions: function (context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; @@ -140289,7 +140663,7 @@ var ts; var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -146592,13 +146966,13 @@ var ts; return { edits: [] }; // TODO: GH#30113 } function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); - changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include - }); + var signature = groupedReferences.signature; + var newFunctionDeclarationParams = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + if (signature) { + var newSignatureParams = ts.map(createNewParameters(signature, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); }); for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) { var call = functionCalls_1[_i]; @@ -146607,6 +146981,15 @@ var ts; changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include }); } } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes(sourceFile, ts.first(declarationOrSignature.parameters), ts.last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include + }); + } } function getGroupedReferences(functionDeclaration, program, cancellationToken) { var functionNames = getFunctionNames(functionDeclaration); @@ -146625,12 +147008,38 @@ var ts; var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation); var classSymbols = ts.map(classNames, getSymbolTargetAtLocation); var isConstructor = ts.isConstructorDeclaration(functionDeclaration); + var contextualSymbols = ts.map(functionNames, function (name) { return getSymbolForContextualType(name, checker); }); for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { var entry = referenceEntries_1[_i]; - if (entry.kind !== 1 /* Node */) { + if (entry.kind === 0 /* Span */) { groupedReferences.valid = false; continue; } + /* Declarations in object literals may be implementations of method signatures which have a different symbol from the declaration + For example: + interface IFoo { m(a: number): void } + const foo: IFoo = { m(a: number): void {} } + In these cases we get the symbol for the signature from the contextual type. + */ + if (ts.contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences.signature = entry.node.parent; + continue; + } + var call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + var contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && ts.contains(contextualSymbols, contextualSymbol)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + } /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: class A { foo(a: number, b: number) { return a + b; } } @@ -146693,6 +147102,19 @@ var ts; return symbol && ts.getSymbolTarget(symbol, checker); } } + /** + * Gets the symbol for the contextual type of the node if it is not a union or intersection. + */ + function getSymbolForContextualType(node, checker) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = checker.getContextualTypeForObjectLiteralElement(element); + var symbol = contextualType === null || contextualType === void 0 ? void 0 : contextualType.getSymbol(); + if (symbol && !(ts.getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } function entryToImportOrExport(entry) { var node = entry.node; if (ts.isImportSpecifier(node.parent) @@ -146800,6 +147222,9 @@ var ts; } return false; } + function isValidMethodSignature(node) { + return ts.isMethodSignature(node) && (ts.isInterfaceDeclaration(node.parent) || ts.isTypeLiteralNode(node.parent)); + } function isValidFunctionDeclaration(functionDeclaration, checker) { if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; @@ -146807,6 +147232,11 @@ var ts; case 251 /* FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); case 165 /* MethodDeclaration */: + if (ts.isObjectLiteralExpression(functionDeclaration.parent)) { + var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change + return (contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } return isSingleImplementation(functionDeclaration, checker); case 166 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { @@ -148429,7 +148859,7 @@ var ts; }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); throw new ts.OperationCanceledException(); } }; @@ -148459,7 +148889,7 @@ var ts; }; ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); throw new ts.OperationCanceledException(); } }; @@ -149140,8 +149570,8 @@ var ts; ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition(fileName, position) { - return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + function getDocCommentTemplateAtPosition(fileName, position, options) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -150945,9 +151375,9 @@ var ts; return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; - LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ @@ -153587,11 +154017,14 @@ var ts; /*@internal*/ Project.prototype.updateTypingFiles = function (typingFiles) { var _this = this; - ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), - /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); }); - this.typingFiles = typingFiles; - // Invalidate files with unresolved imports - this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + if (ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), + /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); })) { + // If typing files changed, then only schedule project update + this.typingFiles = typingFiles; + // Invalidate files with unresolved imports + this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } }; /* @internal */ Project.prototype.getCurrentProgram = function () { @@ -154043,6 +154476,10 @@ var ts; Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { var _this = this; this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); + if (!pluginConfigEntry.name || ts.parsePackageName(pluginConfigEntry.name).rest) { + this.projectService.logger.info("Skipped loading plugin " + (pluginConfigEntry.name || JSON.stringify(pluginConfigEntry)) + " because only package name is allowed plugin name"); + return; + } var log = function (message) { return _this.projectService.logger.info(message); }; var errorLogs; var logError = function (message) { (errorLogs || (errorLogs = [])).push(message); }; @@ -154772,7 +155209,7 @@ var ts; var defaultTypeSafeList = { "jquery": { // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") - match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, + match: /jquery(-[\d\.]+)?(\.intellisense)?(\.min)?\.js$/i, types: ["jquery"] }, "WinJS": { @@ -155231,13 +155668,12 @@ var ts; case server.ActionSet: // Update the typing files and update the project project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); - break; + return; case server.ActionInvalidate: // Do not clear resolution cache, there was changes detected in typings, so enque typing request and let it get us correct results this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ true); return; } - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); }; /*@internal*/ ProjectService.prototype.delayEnsureProjectForOpenFiles = function () { @@ -156144,6 +156580,7 @@ var ts; }; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { + var _this = this; if (options && options.disableSizeLimit || !this.host.getFileSize) { return; } @@ -156159,25 +156596,17 @@ var ts; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + var top5LargestFiles = fileNames.map(function (f) { return propertyReader.getFileName(f); }) + .filter(function (name) { return !ts.hasTSFileExtension(name); }) + .map(function (name) { return ({ name: name, size: _this.host.getFileSize(name) }); }) + .sort(function (a, b) { return b.size - a.size; }) + .slice(0, 5); + this.logger.info("Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + top5LargestFiles.map(function (file) { return file.name + ":" + file.size; }).join(", ")); // Keep the size as zero since it's disabled return fileName; } } this.projectToSizeMap.set(name, totalNonTsFileSize); - return; - function getExceedLimitMessage(context, totalNonTsFileSize) { - var files = getTop5LargestFiles(context); - return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); - } - function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; - return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTSFileExtension(name); }) - .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217 - .sort(function (a, b) { return b.size - a.size; }) - .slice(0, 5); - } }; ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) { var compilerOptions = convertCompilerOptions(options); @@ -158188,24 +158617,24 @@ var ts; try { if (this.operationHost.isCancellationRequested()) { stop = true; - ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId, early: true }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId, early: true }); } else { - ts.tracing.push("session" /* Session */, "stepAction", { seq: this.requestId }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* Session */, "stepAction", { seq: this.requestId }); action(this); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } catch (e) { // Cancellation or an error may have left incomplete events on the tracing stack. - ts.tracing.popAll(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.popAll(); stop = true; // ignore cancellation request if (e instanceof ts.OperationCanceledException) { - ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId }); } else { - ts.tracing.instant("session" /* Session */, "stepError", { seq: this.requestId, message: e.message }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepError", { seq: this.requestId, message: e.message }); this.operationHost.logError(e, "delayed processing of request " + this.requestId); } } @@ -159135,7 +159564,7 @@ var ts; this.host.write(msgText); }; Session.prototype.event = function (body, eventName) { - ts.tracing.instant("session" /* Session */, "event", { eventName: eventName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "event", { eventName: eventName }); this.send(toEvent(eventName, body)); }; // For backwards-compatibility only. @@ -159286,7 +159715,8 @@ var ts; }; Session.prototype.getEncodedSemanticClassifications = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - return project.getLanguageService().getEncodedSemanticClassifications(file, args); + var format = args.format === "2020" ? "2020" /* TwentyTwenty */ : "original" /* Original */; + return project.getLanguageService().getEncodedSemanticClassifications(file, args, format); }; Session.prototype.getProject = function (projectFileName) { return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName); @@ -159714,7 +160144,7 @@ var ts; Session.prototype.getDocCommentTemplate = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var position = this.getPositionInFile(args, file); - return languageService.getDocCommentTemplateAtPosition(file, position); + return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file)); }; Session.prototype.getSpanOfEnclosingComment = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -160507,11 +160937,11 @@ var ts; try { request = this.parseMessage(message); relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; - ts.tracing.instant("session" /* Session */, "request", { seq: request.seq, command: request.command }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "request", { seq: request.seq, command: request.command }); ts.perfLogger.logStartCommand("" + request.command, this.toStringMessage(message).substring(0, 100)); - ts.tracing.push("session" /* Session */, "executeCommand", { seq: request.seq, command: request.command }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* Session */, "executeCommand", { seq: request.seq, command: request.command }, /*separateBeginAndEnd*/ true); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); if (responseRequired) { @@ -160523,7 +160953,7 @@ var ts; } // Note: Log before writing the response, else the editor can complete its activity before the server does ts.perfLogger.logStopCommand("" + request.command, "Success"); - ts.tracing.instant("session" /* Session */, "response", { seq: request.seq, command: request.command, success: !!response }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "response", { seq: request.seq, command: request.command, success: !!response }); if (response) { this.doOutput(response, request.command, request.seq, /*success*/ true); } @@ -160533,17 +160963,17 @@ var ts; } catch (err) { // Cancellation or an error may have left incomplete events on the tracing stack. - ts.tracing.popAll(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.popAll(); if (err instanceof ts.OperationCanceledException) { // Handle cancellation exceptions ts.perfLogger.logStopCommand("" + (request && request.command), "Canceled: " + err); - ts.tracing.instant("session" /* Session */, "commandCanceled", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "commandCanceled", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command }); this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } this.logErrorWorker(err, this.toStringMessage(message), relevantFile); ts.perfLogger.logStopCommand("" + (request && request.command), "Error: " + err); - ts.tracing.instant("session" /* Session */, "commandError", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command, message: err.message }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "commandError", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command, message: err.message }); this.doOutput( /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); @@ -163164,9 +163594,7 @@ var ts; IOSession.prototype.exit = function () { this.logger.info("Exiting..."); this.projectService.closeLog(); - if (traceDir) { - ts.tracing.stopTracing(ts.emptyArray); - } + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.stopTracing(ts.emptyArray); process.exit(0); }; IOSession.prototype.listen = function () { @@ -163193,7 +163621,7 @@ var ts; ? ts.stripQuotes(commandLineTraceDir) : process.env.TSS_TRACE; if (traceDir) { - ts.tracing.startTracing(2 /* Server */, traceDir); + ts.startTracing(2 /* Server */, traceDir); } var ioSession = new IOSession(); process.on("uncaughtException", function (err) { diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index be9c82b1e1d9f..be1c47fd86a47 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -2656,8 +2656,6 @@ declare namespace ts { export interface TemplateLiteralType extends InstantiableType { texts: readonly string[]; types: readonly Type[]; - freshType: TemplateLiteralType; - regularType: TemplateLiteralType; } export interface StringMappingType extends InstantiableType { symbol: Symbol; @@ -3970,6 +3968,7 @@ declare namespace ts { reScanJsxToken(): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; + reScanInvalidIdentifier(): SyntaxKind; scanJsxToken(): JsxTokenSyntaxKind; scanJsDocToken(): JSDocSyntaxKind; scan(): SyntaxKind; @@ -5556,7 +5555,7 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; + getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; /** * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. @@ -6021,11 +6020,15 @@ declare namespace ts { interface RenameInfoOptions { readonly allowRenameOfImportPath?: boolean; } + interface DocCommentTemplateOptions { + readonly generateReturnInDocTemplate?: boolean; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; displayParts: SymbolDisplayPart[]; isOptional: boolean; + isRest?: boolean; } interface SelectionRange { textSpan: TextSpan; @@ -9046,6 +9049,7 @@ declare namespace ts.server.protocol { readonly provideRefactorNotApplicableReason?: boolean; readonly allowRenameOfImportPath?: boolean; readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; + readonly generateReturnInDocTemplate?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -9267,7 +9271,6 @@ declare namespace ts.server { private missingFilesMap; private generatedFilesMap; private plugins; - private lastFileExceededProgramSize; protected languageService: LanguageService; languageServiceEnabled: boolean; readonly trace?: (s: string) => void; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index d565585d0ab2b..ee3a343724bd9 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -3405,16 +3405,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3422,27 +3428,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); } - }, - PerformanceObserver: PerformanceObserver_1 + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); + } + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3473,7 +3478,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3504,6 +3508,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3512,7 +3519,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3525,7 +3538,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3559,40 +3579,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3636,39 +3657,41 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { + // enable the above using startTracing() +})(ts || (ts = {})); +// `tracingEnabled` should never be used directly, only through the above +/* @internal */ +(function (ts) { + var tracingEnabled; + (function (tracingEnabled) { var Mode; (function (Mode) { Mode[Mode["Project"] = 0] = "Project"; Mode[Mode["Build"] = 1] = "Build"; Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + })(Mode = tracingEnabled.Mode || (tracingEnabled.Mode = {})); var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); @@ -3677,9 +3700,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount + : mode === 2 /* Server */ ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3688,24 +3711,21 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; + ts.tracing = undefined; if (typeCatalog) { dumpTypes(typeCatalog); } @@ -3715,11 +3735,7 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; - } - tracing.isTracing = isTracing; + tracingEnabled.stopTracing = stopTracing; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3729,13 +3745,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3745,45 +3759,40 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) return; @@ -3805,7 +3814,6 @@ var ts; } function dumpTypes(types) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3885,11 +3893,15 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled = ts.tracingEnabled || (ts.tracingEnabled = {})); +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + // define after tracingEnabled is initialized + ts.startTracing = ts.tracingEnabled.startTracing; })(ts || (ts = {})); var ts; (function (ts) { @@ -4884,10 +4896,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -6318,7 +6326,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -7286,6 +7294,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7535,7 +7544,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7845,7 +7854,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -8106,6 +8115,8 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8575,6 +8586,9 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8647,6 +8661,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8719,6 +8734,7 @@ var ts; The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8987,8 +9003,9 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -10118,6 +10135,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -11120,15 +11138,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -11145,6 +11157,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11898,19 +11935,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11921,7 +11961,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -15781,6 +15821,8 @@ var ts; return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; case 203 /* CallExpression */: return node.arguments[0]; + case 256 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -17344,11 +17386,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -18033,6 +18084,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -18734,7 +18791,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -19078,6 +19135,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -19140,19 +19201,33 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + } }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); + var cache = createSymlinkCache(cwd, getCanonicalFileName); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; @@ -19162,15 +19237,15 @@ var ts; var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19554,6 +19629,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -20034,6 +20117,10 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; })(ts || (ts = {})); /* @internal */ var ts; @@ -28636,62 +28723,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 157 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28704,7 +28787,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -29580,8 +29663,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29593,6 +29676,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -34727,6 +34815,7 @@ var ts; function parseTagComments(indent, initialMargin) { var comments = []; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34752,7 +34841,8 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace comments.push(scanner.getTokenText()); break; } @@ -34809,6 +34899,7 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); @@ -34873,11 +34964,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); + var indentText = skipWhitespaceOrAsterisk(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -38301,14 +38392,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38428,7 +38519,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38440,22 +38531,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -40378,14 +40454,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -42544,6 +42620,11 @@ var ts; node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 157 /* QualifiedName */: + if (currentFlow && parent.kind === 176 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; @@ -43371,7 +43452,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -44653,6 +44734,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -45528,6 +45628,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45851,7 +45955,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -47441,7 +47545,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -49239,7 +49344,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49627,15 +49732,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49657,12 +49763,15 @@ var ts; var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -50999,7 +51108,7 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + if (func.kind === 168 /* SetAccessor */ && hasBindableName(func)) { var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); @@ -51495,8 +51604,18 @@ var ts; } if (symbol.flags & 134217728 /* ModuleExports */) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables @@ -52574,10 +52693,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -53818,12 +53937,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -54390,7 +54519,7 @@ var ts; } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); @@ -54599,7 +54728,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 167 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; @@ -54846,6 +54975,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54963,7 +55095,7 @@ var ts; } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); @@ -55565,8 +55697,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55579,7 +55718,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55690,52 +55831,40 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types, primitivesOnly) { + function removeSubtypes(types, hasObjectTypes) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return false; + } + } + count++; + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } @@ -55747,10 +55876,12 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55816,20 +55947,18 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (unionReduction & (1 /* Literal */ | 2 /* Subtype */)) { + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + } + if (unionReduction & 2 /* Subtype */) { + if (!removeSubtypes(typeSet, !!(includes & 524288 /* Object */))) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55919,7 +56048,7 @@ var ts; origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -56151,7 +56280,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -56194,7 +56323,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56244,11 +56373,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56384,7 +56519,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56488,7 +56622,8 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } @@ -56522,7 +56657,7 @@ var ts; if (prop) { if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); @@ -56856,7 +56991,7 @@ var ts; return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56932,6 +57067,21 @@ var ts; } return type; } + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 179 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 179 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; @@ -56939,9 +57089,10 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56957,16 +57108,16 @@ var ts; combinedMapper = mergeTypeMappers(mapper, context.mapper); } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56995,8 +57146,8 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; @@ -57344,11 +57495,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57358,12 +57507,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57745,15 +57894,15 @@ var ts; var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); var newAliasSymbol = aliasSymbol || type.aliasSymbol; - var id = getTypeListId(typeArguments) + (newAliasSymbol ? "@" + getSymbolId(newAliasSymbol) : ""); + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters) + (target.aliasSymbol ? "@" + getSymbolId(target.aliasSymbol) : ""), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); @@ -57911,7 +58060,7 @@ var ts; // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); @@ -57946,7 +58095,7 @@ var ts; // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing // with a combination of infinite generic types that perpetually generate new type identities. We stop // the recursion here by yielding the error type. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } @@ -58982,7 +59131,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -59433,7 +59582,7 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { @@ -59559,9 +59708,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59790,7 +59939,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59825,9 +59974,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -60070,20 +60219,17 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } + if (target.flags & 134217728 /* TemplateLiteral */ && + source.texts.length === target.texts.length && + source.types.length === target.types.length && + ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && + ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { + return -1 /* True */; } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + var constraint = getBaseConstraintOfType(source); + if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) { + resetErrorInfo(saveErrorInfo); + return result; } } else if (source.flags & 268435456 /* StringMapping */) { @@ -60342,7 +60488,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60381,8 +60527,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60395,9 +60541,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -61097,7 +61243,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -61136,7 +61282,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -61520,7 +61666,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61529,7 +61675,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -62971,7 +63117,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -63200,6 +63346,10 @@ var ts; return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); + case 157 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); case 216 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } @@ -63612,7 +63762,27 @@ var ts; if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -64013,7 +64183,7 @@ var ts; if (flowDepth === 2000) { // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -64437,10 +64607,13 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var includesNullable = strictNullChecks && maybeTypeOfKind(type, 98304 /* Nullable */); + var removeNullable = includesNullable && ts.isOptionalChain(access); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); @@ -64863,10 +65036,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -65043,7 +65221,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -65084,7 +65267,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; if (localOrExportSymbol.flags & 32 /* Class */) { @@ -66142,7 +66325,7 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. @@ -66371,6 +66554,8 @@ var ts; var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } + case 225 /* NonNullExpression */: + return getContextualType(parent, contextFlags); case 283 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); case 280 /* JsxAttribute */: @@ -66457,16 +66642,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -67803,7 +67991,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67837,7 +68029,7 @@ var ts; } else { if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); @@ -67856,8 +68048,7 @@ var ts; // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || + if (assignmentKind === 1 /* Definite */ || prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } @@ -67869,7 +68060,7 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); @@ -68517,6 +68708,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68569,8 +68769,7 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; @@ -68774,19 +68973,7 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -70155,7 +70342,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 203 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 233 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -70178,7 +70365,8 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { @@ -72263,7 +72451,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType; } function getContextNode(node) { if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { @@ -72282,7 +72470,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72366,7 +72554,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72374,7 +72562,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72627,7 +72815,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72637,7 +72825,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -73289,7 +73477,7 @@ var ts; if (ts.isPrivateIdentifier(node.name)) { error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; @@ -73373,7 +73561,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -74462,7 +74650,7 @@ var ts; // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74667,11 +74855,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -75155,10 +75347,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -76255,7 +76447,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -77181,7 +77373,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -77373,7 +77565,7 @@ var ts; error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77965,7 +78157,7 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -78001,15 +78193,15 @@ var ts; break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -78928,7 +79120,7 @@ var ts; // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true return !!(target.flags & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78936,13 +79128,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -79181,8 +79374,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -80332,19 +80524,31 @@ var ts; return true; } if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 166 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } @@ -85065,8 +85269,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -85200,7 +85403,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -86137,6 +86340,11 @@ var ts; if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } @@ -96360,7 +96568,7 @@ var ts; var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; - expression = createExportExpression(exportName, expression); + expression = factory.createParenthesizedExpression(createExportExpression(exportName, expression)); } return expression; } @@ -98012,7 +98220,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -98110,7 +98319,7 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { @@ -98403,11 +98612,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98490,6 +98701,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98559,8 +98771,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98584,8 +98796,8 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { @@ -98598,12 +98810,12 @@ var ts; } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; @@ -99300,7 +99512,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99469,6 +99683,8 @@ var ts; } } case 252 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99579,6 +99795,8 @@ var ts; if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99960,9 +100178,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -100558,15 +100776,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -105969,7 +106187,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -106303,7 +106521,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106379,15 +106597,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106425,13 +106643,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106439,7 +106657,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106562,19 +106780,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106582,12 +106800,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -107059,7 +107277,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -107068,7 +107286,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -107114,9 +107332,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107777,13 +107995,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -108042,9 +108260,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -108350,6 +108568,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108879,7 +109100,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108896,7 +109117,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -110625,6 +110846,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -111428,12 +111650,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111447,40 +111665,47 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_15 = ts.forEach(targets, function (p) { return !ts.containsIgnoredPath(p) && cb(p, referenceRedirect === p); }); if (result_15) return result_15; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); var result_16 = cb(option, target === referenceRedirect); if (result_16) return result_16; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111525,9 +111750,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + var state_8 = _loop_24(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_8 === "break") break; } if (allFileNames.size) { @@ -117504,7 +117729,7 @@ var ts; // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = getQuotePreference(sourceFile, preferences); var quoted = JSON.stringify(text); - return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'" : quoted; + return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted; } ts.quote = quote; function isEqualityOperatorKind(kind) { @@ -117871,9 +118096,9 @@ var ts; } ts.firstOrOnly = firstOrOnly; function getNameForExportedSymbol(symbol, scriptTarget) { - if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { + if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); } return symbol.name; @@ -120388,6 +120613,7 @@ var ts; } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) { var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -120875,7 +121101,7 @@ var ts; keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } @@ -120989,13 +121215,34 @@ var ts; ? 6 /* TypeAssertionKeywords */ : 7 /* TypeKeywords */; } + var variableDeclaration = getVariableDeclaration(location); ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { return true; } - symbol = ts.skipAlias(symbol, typeChecker); + // Filter out variables from their own initializers + // `const a = /* no 'a' here */` + if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { + return false; + } + // External modules can have global export declarations that will be + // available as global keywords in all scopes. But if the external module + // already has an explicit export and user only wants to user explicit + // module imports then the global keywords will be filtered out so auto + // import suggestions will win in the completion + var symbolOrigin = ts.skipAlias(symbol, typeChecker); + // We only want to filter out the global keywords + // Auto Imports are not available for scripts so this conditional is always false + if (!!sourceFile.externalModuleIndicator + && !compilerOptions.allowUmdGlobalAccess + && symbolToSortTextMap[ts.getSymbolId(symbol)] === SortText.GlobalsOrKeywords + && symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions) { + return false; + } + // Continue with origin symbol + symbol = symbolOrigin; // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); @@ -121009,6 +121256,18 @@ var ts; return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); }); } + function getVariableDeclaration(property) { + var variableDeclaration = ts.findAncestor(property, function (node) { + return ts.isFunctionBlock(node) || isArrowFunctionBody(node) || ts.isBindingPattern(node) + ? "quit" + : ts.isVariableDeclaration(node); + }); + return variableDeclaration; + } + function isArrowFunctionBody(node) { + return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node; + } + ; function isTypeOnlyCompletion() { return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && @@ -121268,18 +121527,19 @@ var ts; } return false; } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + function isNewIdentifierDefinitionLocation() { + if (contextToken) { + var containingNodeKind = contextToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { + switch (keywordForNode(contextToken)) { case 27 /* CommaToken */: return containingNodeKind === 203 /* CallExpression */ // func( a, | || containingNodeKind === 166 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ || containingNodeKind === 204 /* NewExpression */ // new C(a, | || containingNodeKind === 199 /* ArrayLiteralExpression */ // [a, | || containingNodeKind === 216 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 174 /* FunctionType */; // var x: (s: string, list| + || containingNodeKind === 174 /* FunctionType */ // var x: (s: string, list| + || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { x, | case 20 /* OpenParenToken */: return containingNodeKind === 203 /* CallExpression */ // func( | || containingNodeKind === 166 /* Constructor */ // constructor( | @@ -121296,7 +121556,8 @@ var ts; case 24 /* DotToken */: return containingNodeKind === 256 /* ModuleDeclaration */; // module A.| case 18 /* OpenBraceToken */: - return containingNodeKind === 252 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 252 /* ClassDeclaration */ // class A { | + || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { | case 62 /* EqualsToken */: return containingNodeKind === 249 /* VariableDeclaration */ // const x = a| || containingNodeKind === 216 /* BinaryExpression */; // x = a| @@ -126682,7 +126943,7 @@ var ts; * @param position The (character-indexed) position in the file where the check should * be performed. */ - function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { @@ -126694,7 +126955,7 @@ var ts; if (!existingDocComment && tokenStart < position) { return undefined; } - var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); if (!commentOwnerInfo) { return undefined; } @@ -126744,10 +127005,10 @@ var ts; function returnsDocComment(indentationStr, newLine) { return indentationStr + " * @returns" + newLine; } - function getCommentOwnerInfo(tokenAtPos) { - return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + function getCommentOwnerInfo(tokenAtPos, options) { + return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); }); } - function getCommentOwnerInfoWorker(commentOwner) { + function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { case 251 /* FunctionDeclaration */: case 208 /* FunctionExpression */: @@ -126756,9 +127017,9 @@ var ts; case 164 /* MethodSignature */: case 209 /* ArrowFunction */: var host = commentOwner; - return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host) }; + return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; case 288 /* PropertyAssignment */: - return getCommentOwnerInfoWorker(commentOwner.initializer); + return getCommentOwnerInfoWorker(commentOwner.initializer, options); case 252 /* ClassDeclaration */: case 253 /* InterfaceDeclaration */: case 162 /* PropertySignature */: @@ -126773,7 +127034,7 @@ var ts; ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1) } + ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } : { commentOwner: commentOwner }; } case 297 /* SourceFile */: @@ -126784,26 +127045,27 @@ var ts; // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. return commentOwner.parent.kind === 256 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 233 /* ExpressionStatement */: - return getCommentOwnerInfoWorker(commentOwner.expression); + return getCommentOwnerInfoWorker(commentOwner.expression, options); case 216 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } return ts.isFunctionLike(be.right) - ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right) } + ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner: commentOwner }; } case 163 /* PropertyDeclaration */: var init = commentOwner.initializer; if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { - return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init) }; + return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; } } } - function hasReturn(node) { - return ts.isArrowFunction(node) && ts.isExpression(node.body) - || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; }); + function hasReturn(node, options) { + return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && + (ts.isArrowFunction(node) && ts.isExpression(node.body) + || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { while (rightHandSide.kind === 207 /* ParenthesizedExpression */) { @@ -127101,6 +127363,16 @@ var ts; addChildrenRecursively(child); endNode(); } + function addNodeWithRecursiveInitializer(node) { + if (node.initializer && isFunctionOrClassExpression(node.initializer)) { + startNode(node); + ts.forEachChild(node.initializer, addChildrenRecursively); + endNode(); + } + else { + addNodeWithRecursiveChild(node, node.initializer); + } + } /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node) { var _a; @@ -127130,6 +127402,10 @@ var ts; } break; case 163 /* PropertyDeclaration */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveInitializer(node); + } + break; case 162 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); @@ -127168,21 +127444,16 @@ var ts; break; case 198 /* BindingElement */: case 288 /* PropertyAssignment */: - case 249 /* VariableDeclaration */: - var _e = node, name = _e.name, initializer = _e.initializer; - if (ts.isBindingPattern(name)) { - addChildrenRecursively(name); - } - else if (initializer && isFunctionOrClassExpression(initializer)) { - // Add a node for the VariableDeclaration, but not for the initializer. - startNode(node); - ts.forEachChild(initializer, addChildrenRecursively); - endNode(); + case 249 /* VariableDeclaration */: { + var child = node; + if (ts.isBindingPattern(child.name)) { + addChildrenRecursively(child.name); } else { - addNodeWithRecursiveChild(node, initializer); + addNodeWithRecursiveInitializer(child); } break; + } case 251 /* FunctionDeclaration */: var nameNode = node.name; // If we see a function declaration track as a possible ES5 class @@ -127197,8 +127468,8 @@ var ts; break; case 255 /* EnumDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } @@ -127209,8 +127480,8 @@ var ts; case 221 /* ClassExpression */: case 253 /* InterfaceDeclaration */: startNode(node); - for (var _h = 0, _j = node.members; _h < _j.length; _h++) { - var member = _j[_h]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); @@ -127293,7 +127564,7 @@ var ts; defineCall.arguments[0] : defineCall.arguments[0].expression; var memberName = defineCall.arguments[1]; - var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1]; + var _j = startNestedNodes(node, className), depth = _j[0], classNameIdentifier = _j[1]; startNode(node, classNameIdentifier); startNode(node, ts.setTextRange(ts.factory.createIdentifier(memberName.text), memberName)); addChildrenRecursively(node.arguments[2]); @@ -130225,7 +130496,19 @@ var ts; itemsSeen += item.length; } ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. - return { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var help = { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var selected = help.items[selectedItemIndex]; + if (selected.isVariadic) { + var firstRest = ts.findIndex(selected.parameters, function (p) { return !!p.isRest; }); + if (-1 < firstRest && firstRest < selected.parameters.length - 1) { + // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL + help.argumentIndex = selected.parameters.length; + } + else { + help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1); + } + } + return help; } function createTypeHelpItems(symbol, _a, sourceFile, checker) { var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; @@ -130307,14 +130590,15 @@ var ts; printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); - return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + var isRest = !!(parameter.checkFlags & 32768 /* RestParameter */); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional, isRest: isRest }; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false, isRest: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -130577,7 +130861,7 @@ var ts; return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && - hasReturnStatementWithPromiseHandler(node.body) && + hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker); } function returnsPromise(node, checker) { @@ -130589,23 +130873,23 @@ var ts; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - function hasReturnStatementWithPromiseHandler(body) { - return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + function hasReturnStatementWithPromiseHandler(body, checker) { + return !!ts.forEachReturnStatement(body, function (statement) { return isReturnStatementWithFixablePromiseHandler(statement, checker); }); } - function isReturnStatementWithFixablePromiseHandler(node) { - return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + function isReturnStatementWithFixablePromiseHandler(node, checker) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - function isFixablePromiseHandler(node) { + function isFixablePromiseHandler(node, checker) { // ensure outermost call exists and is a promise handler - if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + if (!isPromiseHandler(node) || !node.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } // ensure all chained calls are valid var currentNode = node.expression; while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { - if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } currentNode = currentNode.expression; @@ -130628,7 +130912,7 @@ var ts; }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts - function isFixablePromiseArgument(arg) { + function isFixablePromiseArgument(arg, checker) { switch (arg.kind) { case 251 /* FunctionDeclaration */: case 208 /* FunctionExpression */: @@ -130636,8 +130920,16 @@ var ts; visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); // falls through case 103 /* NullKeyword */: - case 78 /* Identifier */: // identifier includes undefined return true; + case 78 /* Identifier */: + case 201 /* PropertyAccessExpression */: { + var symbol = checker.getSymbolAtLocation(arg); + if (!symbol) { + return false; + } + return checker.isUndefinedSymbol(symbol) || + ts.some(ts.skipAlias(symbol, checker).declarations, function (d) { return ts.isFunctionLike(d) || ts.hasInitializer(d) && !!d.initializer && ts.isFunctionLike(d.initializer); }); + } default: return false; } @@ -132978,14 +133270,17 @@ var ts; processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } if (!formattingScanner.isOnToken()) { + var indentation = formatting.SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false) + ? initialIndentation + options.indentSize + : initialIndentation; var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); - if (options.trimTrailingWhitespace !== false) { - trimTrailingWhitespacesForRemainingRange(); - } + indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); } } + if (options.trimTrailingWhitespace !== false) { + trimTrailingWhitespacesForRemainingRange(); + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -133032,10 +133327,9 @@ var ts; // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; } - else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; - } - else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { @@ -133123,6 +133417,7 @@ var ts; case 275 /* JsxOpeningElement */: case 276 /* JsxClosingElement */: case 274 /* JsxSelfClosingElement */: + case 223 /* ExpressionWithTypeArguments */: return false; } break; @@ -133924,6 +134219,7 @@ var ts; } SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var _a; var parent = current.parent; // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if // * parent and child nodes start on the same line, or @@ -133939,7 +134235,25 @@ var ts; childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + var firstListChild = (_a = getContainingList(current, sourceFile)) === null || _a === void 0 ? void 0 : _a[0]; + // A list indents its children if the children begin on a later line than the list itself: + // + // f1( L0 - List start + // { L1 - First child start: indented, along with all other children + // prop: 0 + // }, + // { + // prop: 1 + // } + // ) + // + // f2({ L0 - List start and first child start: children are not indented. + // prop: 0 Object properties are indented only one level, because the list + // }, { itself contributes nothing. + // prop: 1 L3 - The indentation of the second object literal is best understood by + // }) looking at the relationship between the list and *first* list item. + var listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line; + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -134052,6 +134366,49 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + // A multiline conditional typically increases the indentation of its whenTrue and whenFalse children: + // + // condition + // ? whenTrue + // : whenFalse; + // + // However, that indentation does not apply if the subexpressions themselves span multiple lines, + // applying their own indentation: + // + // (() => { + // return complexCalculationForCondition(); + // })() ? { + // whenTrue: 'multiline object literal' + // } : ( + // whenFalse('multiline parenthesized expression') + // ); + // + // In these cases, we must discard the indentation increase that would otherwise be applied to the + // whenTrue and whenFalse children to avoid double-indenting their contents. To identify this scenario, + // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse + // branch beginning on the line that the whenTrue branch ends. + function childIsUnindentedBranchOfConditionalExpression(parent, child, childStartLine, sourceFile) { + if (ts.isConditionalExpression(parent) && (child === parent.whenTrue || child === parent.whenFalse)) { + var conditionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.condition.end).line; + if (child === parent.whenTrue) { + return childStartLine === conditionEndLine; + } + else { + // On the whenFalse side, we have to look at the whenTrue side, because if that one was + // indented, whenFalse must also be indented: + // + // const y = true + // ? 1 : ( L1: whenTrue indented because it's on a new line + // 0 L2: indented two stops, one because whenTrue was indented + // ); and one because of the parentheses spanning multiple lines + var trueStartLine = getStartLineAndCharacterForNode(parent.whenTrue, sourceFile).line; + var trueEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.whenTrue.end).line; + return conditionEndLine === trueStartLine && trueEndLine === childStartLine; + } + } + return false; + } + SmartIndenter.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) { if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) @@ -134297,7 +134654,7 @@ var ts; if (childKind === 177 /* TypeLiteral */ || childKind === 179 /* TupleType */) { return false; } - // falls through + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -135780,7 +136137,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + errorCodes: [ + ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], getCodeActions: function (context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { @@ -136792,7 +137152,7 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); - var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; @@ -136818,10 +137178,10 @@ var ts; _loop_12(returnStatement); } } - function getReturnStatementsWithPromiseHandlers(body) { + function getReturnStatementsWithPromiseHandlers(body, checker) { var res = []; ts.forEachReturnStatement(body, function (ret) { - if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + if (ts.isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; @@ -137070,6 +137430,7 @@ var ts; case 103 /* NullKeyword */: // do not produce a transformed statement for a null argument break; + case 201 /* PropertyAccessExpression */: case 78 /* Identifier */: // identifier includes undefined if (!argName) { // undefined was argument passed to promise handler @@ -137103,7 +137464,7 @@ var ts; var statement = _f[_i]; if (ts.isReturnStatement(statement)) { seenReturnStatement = true; - if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + if (ts.isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -137120,7 +137481,7 @@ var ts; : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); } else { - var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; + var innerRetStmts = ts.isFixablePromiseHandler(funcBody, transformer.checker) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return innerCbBody; @@ -137213,6 +137574,9 @@ var ts; else if (ts.isIdentifier(funcNode)) { name = getMapEntryOrDefault(funcNode); } + else if (ts.isPropertyAccessExpression(funcNode) && ts.isIdentifier(funcNode.name)) { + name = getMapEntryOrDefault(funcNode.name); + } // return undefined argName when arg is null or undefined // eslint-disable-next-line no-in-operator if (!name || "identifier" in name && name.identifier.text === "undefined") { @@ -138203,7 +138567,7 @@ var ts; : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; + var moduleSpecifier = getBestFix(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences), sourceFile, program, host).moduleSpecifier; var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } @@ -138211,7 +138575,7 @@ var ts; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); + return getBestFix(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, program, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -138390,8 +138754,7 @@ var ts; function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); - var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + return ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences) .map(function (moduleSpecifier) { @@ -138401,18 +138764,6 @@ var ts; : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; }); }); - // Sort by presence in package.json, then shortest paths first - return ts.sort(choicesForEachExportingModule, function (a, b) { - var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier); - var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier); - if (allowsImportingA && !allowsImportingB) { - return -1; - } - if (allowsImportingB && !allowsImportingA) { - return 1; - } - return a.moduleSpecifier.length - b.moduleSpecifier.length; - }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); @@ -138433,7 +138784,28 @@ var ts; var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, context.host) }); + } + function sortFixes(fixes, sourceFile, program, host) { + var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier); }); + } + function getBestFix(fixes, sourceFile, program, host) { + // These will always be placed first if available, and are better than other kinds + if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { + return fixes[0]; + } + var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; + return fixes.reduce(function (best, fix) { + return compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + }); + } + function compareModuleSpecifiers(a, b, allowsImportingSpecifier) { + if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { + return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + } + return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; @@ -138540,7 +138912,7 @@ var ts; if (!exported) return undefined; var symbol = exported.symbol, kind = exported.kind; - var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + var info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); return info && __assign({ symbol: symbol, kind: kind }, info); } function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) { @@ -138575,7 +138947,7 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -138589,21 +138961,20 @@ var ts; // but we can still offer completions for it. // - `aliased.parent` will be undefined if the module is exporting `globalThis.something`, // or another expression that resolves to a global. - return getDefaultExportInfoWorker(aliased, aliased.parent, checker, compilerOptions); + return getDefaultExportInfoWorker(aliased, checker, compilerOptions); } } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + return { symbolForMeaning: defaultExport, name: ts.getNameForExportedSymbol(defaultExport, compilerOptions.target) }; } function getNameForExportDefault(symbol) { return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + var _a; if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.text; - } + return (_a = ts.tryCast(ts.skipOuterExpressions(declaration.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export"); @@ -140100,7 +140471,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + errorCodes: [ + ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ], getCodeActions: function (context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; @@ -140858,7 +141232,7 @@ var ts; var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -147161,13 +147535,13 @@ var ts; return { edits: [] }; // TODO: GH#30113 } function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); - changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include - }); + var signature = groupedReferences.signature; + var newFunctionDeclarationParams = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + if (signature) { + var newSignatureParams = ts.map(createNewParameters(signature, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); }); for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) { var call = functionCalls_1[_i]; @@ -147176,6 +147550,15 @@ var ts; changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include }); } } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes(sourceFile, ts.first(declarationOrSignature.parameters), ts.last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include + }); + } } function getGroupedReferences(functionDeclaration, program, cancellationToken) { var functionNames = getFunctionNames(functionDeclaration); @@ -147194,12 +147577,38 @@ var ts; var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation); var classSymbols = ts.map(classNames, getSymbolTargetAtLocation); var isConstructor = ts.isConstructorDeclaration(functionDeclaration); + var contextualSymbols = ts.map(functionNames, function (name) { return getSymbolForContextualType(name, checker); }); for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { var entry = referenceEntries_1[_i]; - if (entry.kind !== 1 /* Node */) { + if (entry.kind === 0 /* Span */) { groupedReferences.valid = false; continue; } + /* Declarations in object literals may be implementations of method signatures which have a different symbol from the declaration + For example: + interface IFoo { m(a: number): void } + const foo: IFoo = { m(a: number): void {} } + In these cases we get the symbol for the signature from the contextual type. + */ + if (ts.contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences.signature = entry.node.parent; + continue; + } + var call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + var contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && ts.contains(contextualSymbols, contextualSymbol)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + } /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: class A { foo(a: number, b: number) { return a + b; } } @@ -147262,6 +147671,19 @@ var ts; return symbol && ts.getSymbolTarget(symbol, checker); } } + /** + * Gets the symbol for the contextual type of the node if it is not a union or intersection. + */ + function getSymbolForContextualType(node, checker) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = checker.getContextualTypeForObjectLiteralElement(element); + var symbol = contextualType === null || contextualType === void 0 ? void 0 : contextualType.getSymbol(); + if (symbol && !(ts.getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } function entryToImportOrExport(entry) { var node = entry.node; if (ts.isImportSpecifier(node.parent) @@ -147369,6 +147791,9 @@ var ts; } return false; } + function isValidMethodSignature(node) { + return ts.isMethodSignature(node) && (ts.isInterfaceDeclaration(node.parent) || ts.isTypeLiteralNode(node.parent)); + } function isValidFunctionDeclaration(functionDeclaration, checker) { if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; @@ -147376,6 +147801,11 @@ var ts; case 251 /* FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); case 165 /* MethodDeclaration */: + if (ts.isObjectLiteralExpression(functionDeclaration.parent)) { + var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change + return (contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } return isSingleImplementation(functionDeclaration, checker); case 166 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { @@ -148998,7 +149428,7 @@ var ts; }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); throw new ts.OperationCanceledException(); } }; @@ -149028,7 +149458,7 @@ var ts; }; ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); throw new ts.OperationCanceledException(); } }; @@ -149709,8 +150139,8 @@ var ts; ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition(fileName, position) { - return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + function getDocCommentTemplateAtPosition(fileName, position, options) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -151514,9 +151944,9 @@ var ts; return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; - LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ @@ -153781,11 +154211,14 @@ var ts; /*@internal*/ Project.prototype.updateTypingFiles = function (typingFiles) { var _this = this; - ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), - /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); }); - this.typingFiles = typingFiles; - // Invalidate files with unresolved imports - this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + if (ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), + /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); })) { + // If typing files changed, then only schedule project update + this.typingFiles = typingFiles; + // Invalidate files with unresolved imports + this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } }; /* @internal */ Project.prototype.getCurrentProgram = function () { @@ -154237,6 +154670,10 @@ var ts; Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { var _this = this; this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); + if (!pluginConfigEntry.name || ts.parsePackageName(pluginConfigEntry.name).rest) { + this.projectService.logger.info("Skipped loading plugin " + (pluginConfigEntry.name || JSON.stringify(pluginConfigEntry)) + " because only package name is allowed plugin name"); + return; + } var log = function (message) { return _this.projectService.logger.info(message); }; var errorLogs; var logError = function (message) { (errorLogs || (errorLogs = [])).push(message); }; @@ -154966,7 +155403,7 @@ var ts; var defaultTypeSafeList = { "jquery": { // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") - match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, + match: /jquery(-[\d\.]+)?(\.intellisense)?(\.min)?\.js$/i, types: ["jquery"] }, "WinJS": { @@ -155425,13 +155862,12 @@ var ts; case server.ActionSet: // Update the typing files and update the project project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); - break; + return; case server.ActionInvalidate: // Do not clear resolution cache, there was changes detected in typings, so enque typing request and let it get us correct results this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ true); return; } - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); }; /*@internal*/ ProjectService.prototype.delayEnsureProjectForOpenFiles = function () { @@ -156338,6 +156774,7 @@ var ts; }; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { + var _this = this; if (options && options.disableSizeLimit || !this.host.getFileSize) { return; } @@ -156353,25 +156790,17 @@ var ts; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + var top5LargestFiles = fileNames.map(function (f) { return propertyReader.getFileName(f); }) + .filter(function (name) { return !ts.hasTSFileExtension(name); }) + .map(function (name) { return ({ name: name, size: _this.host.getFileSize(name) }); }) + .sort(function (a, b) { return b.size - a.size; }) + .slice(0, 5); + this.logger.info("Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + top5LargestFiles.map(function (file) { return file.name + ":" + file.size; }).join(", ")); // Keep the size as zero since it's disabled return fileName; } } this.projectToSizeMap.set(name, totalNonTsFileSize); - return; - function getExceedLimitMessage(context, totalNonTsFileSize) { - var files = getTop5LargestFiles(context); - return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); - } - function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; - return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTSFileExtension(name); }) - .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217 - .sort(function (a, b) { return b.size - a.size; }) - .slice(0, 5); - } }; ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) { var compilerOptions = convertCompilerOptions(options); @@ -158382,24 +158811,24 @@ var ts; try { if (this.operationHost.isCancellationRequested()) { stop = true; - ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId, early: true }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId, early: true }); } else { - ts.tracing.push("session" /* Session */, "stepAction", { seq: this.requestId }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* Session */, "stepAction", { seq: this.requestId }); action(this); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } catch (e) { // Cancellation or an error may have left incomplete events on the tracing stack. - ts.tracing.popAll(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.popAll(); stop = true; // ignore cancellation request if (e instanceof ts.OperationCanceledException) { - ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId }); } else { - ts.tracing.instant("session" /* Session */, "stepError", { seq: this.requestId, message: e.message }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepError", { seq: this.requestId, message: e.message }); this.operationHost.logError(e, "delayed processing of request " + this.requestId); } } @@ -159329,7 +159758,7 @@ var ts; this.host.write(msgText); }; Session.prototype.event = function (body, eventName) { - ts.tracing.instant("session" /* Session */, "event", { eventName: eventName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "event", { eventName: eventName }); this.send(toEvent(eventName, body)); }; // For backwards-compatibility only. @@ -159480,7 +159909,8 @@ var ts; }; Session.prototype.getEncodedSemanticClassifications = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - return project.getLanguageService().getEncodedSemanticClassifications(file, args); + var format = args.format === "2020" ? "2020" /* TwentyTwenty */ : "original" /* Original */; + return project.getLanguageService().getEncodedSemanticClassifications(file, args, format); }; Session.prototype.getProject = function (projectFileName) { return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName); @@ -159908,7 +160338,7 @@ var ts; Session.prototype.getDocCommentTemplate = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var position = this.getPositionInFile(args, file); - return languageService.getDocCommentTemplateAtPosition(file, position); + return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file)); }; Session.prototype.getSpanOfEnclosingComment = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -160701,11 +161131,11 @@ var ts; try { request = this.parseMessage(message); relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; - ts.tracing.instant("session" /* Session */, "request", { seq: request.seq, command: request.command }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "request", { seq: request.seq, command: request.command }); ts.perfLogger.logStartCommand("" + request.command, this.toStringMessage(message).substring(0, 100)); - ts.tracing.push("session" /* Session */, "executeCommand", { seq: request.seq, command: request.command }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* Session */, "executeCommand", { seq: request.seq, command: request.command }, /*separateBeginAndEnd*/ true); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); if (responseRequired) { @@ -160717,7 +161147,7 @@ var ts; } // Note: Log before writing the response, else the editor can complete its activity before the server does ts.perfLogger.logStopCommand("" + request.command, "Success"); - ts.tracing.instant("session" /* Session */, "response", { seq: request.seq, command: request.command, success: !!response }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "response", { seq: request.seq, command: request.command, success: !!response }); if (response) { this.doOutput(response, request.command, request.seq, /*success*/ true); } @@ -160727,17 +161157,17 @@ var ts; } catch (err) { // Cancellation or an error may have left incomplete events on the tracing stack. - ts.tracing.popAll(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.popAll(); if (err instanceof ts.OperationCanceledException) { // Handle cancellation exceptions ts.perfLogger.logStopCommand("" + (request && request.command), "Canceled: " + err); - ts.tracing.instant("session" /* Session */, "commandCanceled", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "commandCanceled", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command }); this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } this.logErrorWorker(err, this.toStringMessage(message), relevantFile); ts.perfLogger.logStopCommand("" + (request && request.command), "Error: " + err); - ts.tracing.instant("session" /* Session */, "commandError", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command, message: err.message }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "commandError", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command, message: err.message }); this.doOutput( /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index f8f86d5b88fb2..bba168d37e720 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -2656,8 +2656,6 @@ declare namespace ts { export interface TemplateLiteralType extends InstantiableType { texts: readonly string[]; types: readonly Type[]; - freshType: TemplateLiteralType; - regularType: TemplateLiteralType; } export interface StringMappingType extends InstantiableType { symbol: Symbol; @@ -3970,6 +3968,7 @@ declare namespace ts { reScanJsxToken(): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; + reScanInvalidIdentifier(): SyntaxKind; scanJsxToken(): JsxTokenSyntaxKind; scanJsDocToken(): JSDocSyntaxKind; scan(): SyntaxKind; @@ -5556,7 +5555,7 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; + getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; /** * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. @@ -6021,11 +6020,15 @@ declare namespace ts { interface RenameInfoOptions { readonly allowRenameOfImportPath?: boolean; } + interface DocCommentTemplateOptions { + readonly generateReturnInDocTemplate?: boolean; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; displayParts: SymbolDisplayPart[]; isOptional: boolean; + isRest?: boolean; } interface SelectionRange { textSpan: TextSpan; diff --git a/lib/typescript.js b/lib/typescript.js index f2d035ad3f94c..4ccac1a141ac4 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -3405,16 +3405,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3422,27 +3428,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); } - }, - PerformanceObserver: PerformanceObserver_1 + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); + } + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3473,7 +3478,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3504,6 +3508,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3512,7 +3519,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3525,7 +3538,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3559,40 +3579,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3636,39 +3657,41 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { + // enable the above using startTracing() +})(ts || (ts = {})); +// `tracingEnabled` should never be used directly, only through the above +/* @internal */ +(function (ts) { + var tracingEnabled; + (function (tracingEnabled) { var Mode; (function (Mode) { Mode[Mode["Project"] = 0] = "Project"; Mode[Mode["Build"] = 1] = "Build"; Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + })(Mode = tracingEnabled.Mode || (tracingEnabled.Mode = {})); var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); @@ -3677,9 +3700,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount + : mode === 2 /* Server */ ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3688,24 +3711,21 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; + ts.tracing = undefined; if (typeCatalog) { dumpTypes(typeCatalog); } @@ -3715,11 +3735,7 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; - } - tracing.isTracing = isTracing; + tracingEnabled.stopTracing = stopTracing; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3729,13 +3745,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3745,45 +3759,40 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) return; @@ -3805,7 +3814,6 @@ var ts; } function dumpTypes(types) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3885,11 +3893,15 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled = ts.tracingEnabled || (ts.tracingEnabled = {})); +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + // define after tracingEnabled is initialized + ts.startTracing = ts.tracingEnabled.startTracing; })(ts || (ts = {})); var ts; (function (ts) { @@ -4884,10 +4896,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -6318,7 +6326,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -7286,6 +7294,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7535,7 +7544,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7845,7 +7854,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -8106,6 +8115,8 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8575,6 +8586,9 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8647,6 +8661,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8719,6 +8734,7 @@ var ts; The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8987,8 +9003,9 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -10118,6 +10135,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -11120,15 +11138,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -11145,6 +11157,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11898,19 +11935,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11921,7 +11961,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -15781,6 +15821,8 @@ var ts; return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; case 203 /* CallExpression */: return node.arguments[0]; + case 256 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -17344,11 +17386,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -18033,6 +18084,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -18734,7 +18791,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -19078,6 +19135,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -19140,19 +19201,33 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + } }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); + var cache = createSymlinkCache(cwd, getCanonicalFileName); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; @@ -19162,15 +19237,15 @@ var ts; var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19554,6 +19629,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -20034,6 +20117,10 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; })(ts || (ts = {})); /* @internal */ var ts; @@ -28636,62 +28723,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 157 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28704,7 +28787,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -29580,8 +29663,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29593,6 +29676,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -34727,6 +34815,7 @@ var ts; function parseTagComments(indent, initialMargin) { var comments = []; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34752,7 +34841,8 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace comments.push(scanner.getTokenText()); break; } @@ -34809,6 +34899,7 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); @@ -34873,11 +34964,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); + var indentText = skipWhitespaceOrAsterisk(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -38301,14 +38392,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38428,7 +38519,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38440,22 +38531,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -40378,14 +40454,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -42544,6 +42620,11 @@ var ts; node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 157 /* QualifiedName */: + if (currentFlow && parent.kind === 176 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; @@ -43371,7 +43452,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -44653,6 +44734,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -45528,6 +45628,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45851,7 +45955,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -47441,7 +47545,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -49239,7 +49344,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49627,15 +49732,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49657,12 +49763,15 @@ var ts; var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -50999,7 +51108,7 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + if (func.kind === 168 /* SetAccessor */ && hasBindableName(func)) { var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); @@ -51495,8 +51604,18 @@ var ts; } if (symbol.flags & 134217728 /* ModuleExports */) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables @@ -52574,10 +52693,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -53818,12 +53937,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -54390,7 +54519,7 @@ var ts; } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); @@ -54599,7 +54728,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 167 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; @@ -54846,6 +54975,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54963,7 +55095,7 @@ var ts; } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); @@ -55565,8 +55697,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55579,7 +55718,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55690,52 +55831,40 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types, primitivesOnly) { + function removeSubtypes(types, hasObjectTypes) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return false; + } + } + count++; + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } @@ -55747,10 +55876,12 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55816,20 +55947,18 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (unionReduction & (1 /* Literal */ | 2 /* Subtype */)) { + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + } + if (unionReduction & 2 /* Subtype */) { + if (!removeSubtypes(typeSet, !!(includes & 524288 /* Object */))) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55919,7 +56048,7 @@ var ts; origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -56151,7 +56280,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -56194,7 +56323,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56244,11 +56373,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56384,7 +56519,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56488,7 +56622,8 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } @@ -56522,7 +56657,7 @@ var ts; if (prop) { if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); @@ -56856,7 +56991,7 @@ var ts; return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56932,6 +57067,21 @@ var ts; } return type; } + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 179 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 179 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; @@ -56939,9 +57089,10 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56957,16 +57108,16 @@ var ts; combinedMapper = mergeTypeMappers(mapper, context.mapper); } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56995,8 +57146,8 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; @@ -57344,11 +57495,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57358,12 +57507,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57745,15 +57894,15 @@ var ts; var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); var newAliasSymbol = aliasSymbol || type.aliasSymbol; - var id = getTypeListId(typeArguments) + (newAliasSymbol ? "@" + getSymbolId(newAliasSymbol) : ""); + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters) + (target.aliasSymbol ? "@" + getSymbolId(target.aliasSymbol) : ""), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); @@ -57911,7 +58060,7 @@ var ts; // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); @@ -57946,7 +58095,7 @@ var ts; // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing // with a combination of infinite generic types that perpetually generate new type identities. We stop // the recursion here by yielding the error type. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } @@ -58982,7 +59131,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -59433,7 +59582,7 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { @@ -59559,9 +59708,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59790,7 +59939,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59825,9 +59974,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -60070,20 +60219,17 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } + if (target.flags & 134217728 /* TemplateLiteral */ && + source.texts.length === target.texts.length && + source.types.length === target.types.length && + ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && + ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { + return -1 /* True */; } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + var constraint = getBaseConstraintOfType(source); + if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) { + resetErrorInfo(saveErrorInfo); + return result; } } else if (source.flags & 268435456 /* StringMapping */) { @@ -60342,7 +60488,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60381,8 +60527,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60395,9 +60541,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -61097,7 +61243,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -61136,7 +61282,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -61520,7 +61666,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61529,7 +61675,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -62971,7 +63117,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -63200,6 +63346,10 @@ var ts; return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); + case 157 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); case 216 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } @@ -63612,7 +63762,27 @@ var ts; if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -64013,7 +64183,7 @@ var ts; if (flowDepth === 2000) { // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -64437,10 +64607,13 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var includesNullable = strictNullChecks && maybeTypeOfKind(type, 98304 /* Nullable */); + var removeNullable = includesNullable && ts.isOptionalChain(access); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); @@ -64863,10 +65036,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -65043,7 +65221,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -65084,7 +65267,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; if (localOrExportSymbol.flags & 32 /* Class */) { @@ -66142,7 +66325,7 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. @@ -66371,6 +66554,8 @@ var ts; var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } + case 225 /* NonNullExpression */: + return getContextualType(parent, contextFlags); case 283 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); case 280 /* JsxAttribute */: @@ -66457,16 +66642,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -67803,7 +67991,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67837,7 +68029,7 @@ var ts; } else { if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); @@ -67856,8 +68048,7 @@ var ts; // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || + if (assignmentKind === 1 /* Definite */ || prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } @@ -67869,7 +68060,7 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); @@ -68517,6 +68708,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68569,8 +68769,7 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; @@ -68774,19 +68973,7 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -70155,7 +70342,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 203 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 233 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -70178,7 +70365,8 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { @@ -72263,7 +72451,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType; } function getContextNode(node) { if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { @@ -72282,7 +72470,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72366,7 +72554,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72374,7 +72562,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72627,7 +72815,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72637,7 +72825,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -73289,7 +73477,7 @@ var ts; if (ts.isPrivateIdentifier(node.name)) { error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; @@ -73373,7 +73561,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -74462,7 +74650,7 @@ var ts; // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74667,11 +74855,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -75155,10 +75347,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -76255,7 +76447,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -77181,7 +77373,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -77373,7 +77565,7 @@ var ts; error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77965,7 +78157,7 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -78001,15 +78193,15 @@ var ts; break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -78928,7 +79120,7 @@ var ts; // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true return !!(target.flags & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78936,13 +79128,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -79181,8 +79374,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -80332,19 +80524,31 @@ var ts; return true; } if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 166 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } @@ -85065,8 +85269,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -85200,7 +85403,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -86137,6 +86340,11 @@ var ts; if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } @@ -96360,7 +96568,7 @@ var ts; var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; - expression = createExportExpression(exportName, expression); + expression = factory.createParenthesizedExpression(createExportExpression(exportName, expression)); } return expression; } @@ -98012,7 +98220,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -98110,7 +98319,7 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { @@ -98403,11 +98612,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98490,6 +98701,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98559,8 +98771,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98584,8 +98796,8 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { @@ -98598,12 +98810,12 @@ var ts; } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; @@ -99300,7 +99512,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99469,6 +99683,8 @@ var ts; } } case 252 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99579,6 +99795,8 @@ var ts; if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99960,9 +100178,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -100558,15 +100776,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -105969,7 +106187,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -106303,7 +106521,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106379,15 +106597,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106425,13 +106643,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106439,7 +106657,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106562,19 +106780,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106582,12 +106800,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -107059,7 +107277,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -107068,7 +107286,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -107114,9 +107332,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107777,13 +107995,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -108042,9 +108260,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -108350,6 +108568,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108879,7 +109100,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108896,7 +109117,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -110625,6 +110846,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -111428,12 +111650,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111447,40 +111665,47 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_15 = ts.forEach(targets, function (p) { return !ts.containsIgnoredPath(p) && cb(p, referenceRedirect === p); }); if (result_15) return result_15; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); var result_16 = cb(option, target === referenceRedirect); if (result_16) return result_16; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111525,9 +111750,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + var state_8 = _loop_24(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_8 === "break") break; } if (allFileNames.size) { @@ -117504,7 +117729,7 @@ var ts; // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = getQuotePreference(sourceFile, preferences); var quoted = JSON.stringify(text); - return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'" : quoted; + return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted; } ts.quote = quote; function isEqualityOperatorKind(kind) { @@ -117871,9 +118096,9 @@ var ts; } ts.firstOrOnly = firstOrOnly; function getNameForExportedSymbol(symbol, scriptTarget) { - if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { + if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); } return symbol.name; @@ -120388,6 +120613,7 @@ var ts; } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) { var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -120875,7 +121101,7 @@ var ts; keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } @@ -120989,13 +121215,34 @@ var ts; ? 6 /* TypeAssertionKeywords */ : 7 /* TypeKeywords */; } + var variableDeclaration = getVariableDeclaration(location); ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { return true; } - symbol = ts.skipAlias(symbol, typeChecker); + // Filter out variables from their own initializers + // `const a = /* no 'a' here */` + if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { + return false; + } + // External modules can have global export declarations that will be + // available as global keywords in all scopes. But if the external module + // already has an explicit export and user only wants to user explicit + // module imports then the global keywords will be filtered out so auto + // import suggestions will win in the completion + var symbolOrigin = ts.skipAlias(symbol, typeChecker); + // We only want to filter out the global keywords + // Auto Imports are not available for scripts so this conditional is always false + if (!!sourceFile.externalModuleIndicator + && !compilerOptions.allowUmdGlobalAccess + && symbolToSortTextMap[ts.getSymbolId(symbol)] === SortText.GlobalsOrKeywords + && symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions) { + return false; + } + // Continue with origin symbol + symbol = symbolOrigin; // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); @@ -121009,6 +121256,18 @@ var ts; return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); }); } + function getVariableDeclaration(property) { + var variableDeclaration = ts.findAncestor(property, function (node) { + return ts.isFunctionBlock(node) || isArrowFunctionBody(node) || ts.isBindingPattern(node) + ? "quit" + : ts.isVariableDeclaration(node); + }); + return variableDeclaration; + } + function isArrowFunctionBody(node) { + return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node; + } + ; function isTypeOnlyCompletion() { return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && @@ -121268,18 +121527,19 @@ var ts; } return false; } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + function isNewIdentifierDefinitionLocation() { + if (contextToken) { + var containingNodeKind = contextToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { + switch (keywordForNode(contextToken)) { case 27 /* CommaToken */: return containingNodeKind === 203 /* CallExpression */ // func( a, | || containingNodeKind === 166 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ || containingNodeKind === 204 /* NewExpression */ // new C(a, | || containingNodeKind === 199 /* ArrayLiteralExpression */ // [a, | || containingNodeKind === 216 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 174 /* FunctionType */; // var x: (s: string, list| + || containingNodeKind === 174 /* FunctionType */ // var x: (s: string, list| + || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { x, | case 20 /* OpenParenToken */: return containingNodeKind === 203 /* CallExpression */ // func( | || containingNodeKind === 166 /* Constructor */ // constructor( | @@ -121296,7 +121556,8 @@ var ts; case 24 /* DotToken */: return containingNodeKind === 256 /* ModuleDeclaration */; // module A.| case 18 /* OpenBraceToken */: - return containingNodeKind === 252 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 252 /* ClassDeclaration */ // class A { | + || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { | case 62 /* EqualsToken */: return containingNodeKind === 249 /* VariableDeclaration */ // const x = a| || containingNodeKind === 216 /* BinaryExpression */; // x = a| @@ -126682,7 +126943,7 @@ var ts; * @param position The (character-indexed) position in the file where the check should * be performed. */ - function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { @@ -126694,7 +126955,7 @@ var ts; if (!existingDocComment && tokenStart < position) { return undefined; } - var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); if (!commentOwnerInfo) { return undefined; } @@ -126744,10 +127005,10 @@ var ts; function returnsDocComment(indentationStr, newLine) { return indentationStr + " * @returns" + newLine; } - function getCommentOwnerInfo(tokenAtPos) { - return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + function getCommentOwnerInfo(tokenAtPos, options) { + return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); }); } - function getCommentOwnerInfoWorker(commentOwner) { + function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { case 251 /* FunctionDeclaration */: case 208 /* FunctionExpression */: @@ -126756,9 +127017,9 @@ var ts; case 164 /* MethodSignature */: case 209 /* ArrowFunction */: var host = commentOwner; - return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host) }; + return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; case 288 /* PropertyAssignment */: - return getCommentOwnerInfoWorker(commentOwner.initializer); + return getCommentOwnerInfoWorker(commentOwner.initializer, options); case 252 /* ClassDeclaration */: case 253 /* InterfaceDeclaration */: case 162 /* PropertySignature */: @@ -126773,7 +127034,7 @@ var ts; ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1) } + ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } : { commentOwner: commentOwner }; } case 297 /* SourceFile */: @@ -126784,26 +127045,27 @@ var ts; // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. return commentOwner.parent.kind === 256 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 233 /* ExpressionStatement */: - return getCommentOwnerInfoWorker(commentOwner.expression); + return getCommentOwnerInfoWorker(commentOwner.expression, options); case 216 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } return ts.isFunctionLike(be.right) - ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right) } + ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner: commentOwner }; } case 163 /* PropertyDeclaration */: var init = commentOwner.initializer; if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { - return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init) }; + return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; } } } - function hasReturn(node) { - return ts.isArrowFunction(node) && ts.isExpression(node.body) - || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; }); + function hasReturn(node, options) { + return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && + (ts.isArrowFunction(node) && ts.isExpression(node.body) + || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { while (rightHandSide.kind === 207 /* ParenthesizedExpression */) { @@ -127101,6 +127363,16 @@ var ts; addChildrenRecursively(child); endNode(); } + function addNodeWithRecursiveInitializer(node) { + if (node.initializer && isFunctionOrClassExpression(node.initializer)) { + startNode(node); + ts.forEachChild(node.initializer, addChildrenRecursively); + endNode(); + } + else { + addNodeWithRecursiveChild(node, node.initializer); + } + } /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node) { var _a; @@ -127130,6 +127402,10 @@ var ts; } break; case 163 /* PropertyDeclaration */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveInitializer(node); + } + break; case 162 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); @@ -127168,21 +127444,16 @@ var ts; break; case 198 /* BindingElement */: case 288 /* PropertyAssignment */: - case 249 /* VariableDeclaration */: - var _e = node, name = _e.name, initializer = _e.initializer; - if (ts.isBindingPattern(name)) { - addChildrenRecursively(name); - } - else if (initializer && isFunctionOrClassExpression(initializer)) { - // Add a node for the VariableDeclaration, but not for the initializer. - startNode(node); - ts.forEachChild(initializer, addChildrenRecursively); - endNode(); + case 249 /* VariableDeclaration */: { + var child = node; + if (ts.isBindingPattern(child.name)) { + addChildrenRecursively(child.name); } else { - addNodeWithRecursiveChild(node, initializer); + addNodeWithRecursiveInitializer(child); } break; + } case 251 /* FunctionDeclaration */: var nameNode = node.name; // If we see a function declaration track as a possible ES5 class @@ -127197,8 +127468,8 @@ var ts; break; case 255 /* EnumDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } @@ -127209,8 +127480,8 @@ var ts; case 221 /* ClassExpression */: case 253 /* InterfaceDeclaration */: startNode(node); - for (var _h = 0, _j = node.members; _h < _j.length; _h++) { - var member = _j[_h]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); @@ -127293,7 +127564,7 @@ var ts; defineCall.arguments[0] : defineCall.arguments[0].expression; var memberName = defineCall.arguments[1]; - var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1]; + var _j = startNestedNodes(node, className), depth = _j[0], classNameIdentifier = _j[1]; startNode(node, classNameIdentifier); startNode(node, ts.setTextRange(ts.factory.createIdentifier(memberName.text), memberName)); addChildrenRecursively(node.arguments[2]); @@ -130225,7 +130496,19 @@ var ts; itemsSeen += item.length; } ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. - return { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var help = { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var selected = help.items[selectedItemIndex]; + if (selected.isVariadic) { + var firstRest = ts.findIndex(selected.parameters, function (p) { return !!p.isRest; }); + if (-1 < firstRest && firstRest < selected.parameters.length - 1) { + // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL + help.argumentIndex = selected.parameters.length; + } + else { + help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1); + } + } + return help; } function createTypeHelpItems(symbol, _a, sourceFile, checker) { var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; @@ -130307,14 +130590,15 @@ var ts; printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); - return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + var isRest = !!(parameter.checkFlags & 32768 /* RestParameter */); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional, isRest: isRest }; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false, isRest: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -130577,7 +130861,7 @@ var ts; return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && - hasReturnStatementWithPromiseHandler(node.body) && + hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker); } function returnsPromise(node, checker) { @@ -130589,23 +130873,23 @@ var ts; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - function hasReturnStatementWithPromiseHandler(body) { - return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + function hasReturnStatementWithPromiseHandler(body, checker) { + return !!ts.forEachReturnStatement(body, function (statement) { return isReturnStatementWithFixablePromiseHandler(statement, checker); }); } - function isReturnStatementWithFixablePromiseHandler(node) { - return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + function isReturnStatementWithFixablePromiseHandler(node, checker) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - function isFixablePromiseHandler(node) { + function isFixablePromiseHandler(node, checker) { // ensure outermost call exists and is a promise handler - if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + if (!isPromiseHandler(node) || !node.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } // ensure all chained calls are valid var currentNode = node.expression; while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { - if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } currentNode = currentNode.expression; @@ -130628,7 +130912,7 @@ var ts; }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts - function isFixablePromiseArgument(arg) { + function isFixablePromiseArgument(arg, checker) { switch (arg.kind) { case 251 /* FunctionDeclaration */: case 208 /* FunctionExpression */: @@ -130636,8 +130920,16 @@ var ts; visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); // falls through case 103 /* NullKeyword */: - case 78 /* Identifier */: // identifier includes undefined return true; + case 78 /* Identifier */: + case 201 /* PropertyAccessExpression */: { + var symbol = checker.getSymbolAtLocation(arg); + if (!symbol) { + return false; + } + return checker.isUndefinedSymbol(symbol) || + ts.some(ts.skipAlias(symbol, checker).declarations, function (d) { return ts.isFunctionLike(d) || ts.hasInitializer(d) && !!d.initializer && ts.isFunctionLike(d.initializer); }); + } default: return false; } @@ -132978,14 +133270,17 @@ var ts; processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } if (!formattingScanner.isOnToken()) { + var indentation = formatting.SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false) + ? initialIndentation + options.indentSize + : initialIndentation; var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); - if (options.trimTrailingWhitespace !== false) { - trimTrailingWhitespacesForRemainingRange(); - } + indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); } } + if (options.trimTrailingWhitespace !== false) { + trimTrailingWhitespacesForRemainingRange(); + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -133032,10 +133327,9 @@ var ts; // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; } - else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; - } - else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { @@ -133123,6 +133417,7 @@ var ts; case 275 /* JsxOpeningElement */: case 276 /* JsxClosingElement */: case 274 /* JsxSelfClosingElement */: + case 223 /* ExpressionWithTypeArguments */: return false; } break; @@ -133924,6 +134219,7 @@ var ts; } SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var _a; var parent = current.parent; // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if // * parent and child nodes start on the same line, or @@ -133939,7 +134235,25 @@ var ts; childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + var firstListChild = (_a = getContainingList(current, sourceFile)) === null || _a === void 0 ? void 0 : _a[0]; + // A list indents its children if the children begin on a later line than the list itself: + // + // f1( L0 - List start + // { L1 - First child start: indented, along with all other children + // prop: 0 + // }, + // { + // prop: 1 + // } + // ) + // + // f2({ L0 - List start and first child start: children are not indented. + // prop: 0 Object properties are indented only one level, because the list + // }, { itself contributes nothing. + // prop: 1 L3 - The indentation of the second object literal is best understood by + // }) looking at the relationship between the list and *first* list item. + var listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line; + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -134052,6 +134366,49 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + // A multiline conditional typically increases the indentation of its whenTrue and whenFalse children: + // + // condition + // ? whenTrue + // : whenFalse; + // + // However, that indentation does not apply if the subexpressions themselves span multiple lines, + // applying their own indentation: + // + // (() => { + // return complexCalculationForCondition(); + // })() ? { + // whenTrue: 'multiline object literal' + // } : ( + // whenFalse('multiline parenthesized expression') + // ); + // + // In these cases, we must discard the indentation increase that would otherwise be applied to the + // whenTrue and whenFalse children to avoid double-indenting their contents. To identify this scenario, + // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse + // branch beginning on the line that the whenTrue branch ends. + function childIsUnindentedBranchOfConditionalExpression(parent, child, childStartLine, sourceFile) { + if (ts.isConditionalExpression(parent) && (child === parent.whenTrue || child === parent.whenFalse)) { + var conditionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.condition.end).line; + if (child === parent.whenTrue) { + return childStartLine === conditionEndLine; + } + else { + // On the whenFalse side, we have to look at the whenTrue side, because if that one was + // indented, whenFalse must also be indented: + // + // const y = true + // ? 1 : ( L1: whenTrue indented because it's on a new line + // 0 L2: indented two stops, one because whenTrue was indented + // ); and one because of the parentheses spanning multiple lines + var trueStartLine = getStartLineAndCharacterForNode(parent.whenTrue, sourceFile).line; + var trueEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.whenTrue.end).line; + return conditionEndLine === trueStartLine && trueEndLine === childStartLine; + } + } + return false; + } + SmartIndenter.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) { if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) @@ -134297,7 +134654,7 @@ var ts; if (childKind === 177 /* TypeLiteral */ || childKind === 179 /* TupleType */) { return false; } - // falls through + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -135780,7 +136137,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + errorCodes: [ + ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], getCodeActions: function (context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { @@ -136792,7 +137152,7 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); - var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; @@ -136818,10 +137178,10 @@ var ts; _loop_12(returnStatement); } } - function getReturnStatementsWithPromiseHandlers(body) { + function getReturnStatementsWithPromiseHandlers(body, checker) { var res = []; ts.forEachReturnStatement(body, function (ret) { - if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + if (ts.isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; @@ -137070,6 +137430,7 @@ var ts; case 103 /* NullKeyword */: // do not produce a transformed statement for a null argument break; + case 201 /* PropertyAccessExpression */: case 78 /* Identifier */: // identifier includes undefined if (!argName) { // undefined was argument passed to promise handler @@ -137103,7 +137464,7 @@ var ts; var statement = _f[_i]; if (ts.isReturnStatement(statement)) { seenReturnStatement = true; - if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + if (ts.isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -137120,7 +137481,7 @@ var ts; : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); } else { - var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; + var innerRetStmts = ts.isFixablePromiseHandler(funcBody, transformer.checker) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return innerCbBody; @@ -137213,6 +137574,9 @@ var ts; else if (ts.isIdentifier(funcNode)) { name = getMapEntryOrDefault(funcNode); } + else if (ts.isPropertyAccessExpression(funcNode) && ts.isIdentifier(funcNode.name)) { + name = getMapEntryOrDefault(funcNode.name); + } // return undefined argName when arg is null or undefined // eslint-disable-next-line no-in-operator if (!name || "identifier" in name && name.identifier.text === "undefined") { @@ -138203,7 +138567,7 @@ var ts; : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; + var moduleSpecifier = getBestFix(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences), sourceFile, program, host).moduleSpecifier; var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } @@ -138211,7 +138575,7 @@ var ts; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); + return getBestFix(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, program, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -138390,8 +138754,7 @@ var ts; function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); - var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + return ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences) .map(function (moduleSpecifier) { @@ -138401,18 +138764,6 @@ var ts; : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; }); }); - // Sort by presence in package.json, then shortest paths first - return ts.sort(choicesForEachExportingModule, function (a, b) { - var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier); - var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier); - if (allowsImportingA && !allowsImportingB) { - return -1; - } - if (allowsImportingB && !allowsImportingA) { - return 1; - } - return a.moduleSpecifier.length - b.moduleSpecifier.length; - }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); @@ -138433,7 +138784,28 @@ var ts; var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, context.host) }); + } + function sortFixes(fixes, sourceFile, program, host) { + var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier); }); + } + function getBestFix(fixes, sourceFile, program, host) { + // These will always be placed first if available, and are better than other kinds + if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { + return fixes[0]; + } + var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; + return fixes.reduce(function (best, fix) { + return compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + }); + } + function compareModuleSpecifiers(a, b, allowsImportingSpecifier) { + if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { + return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + } + return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; @@ -138540,7 +138912,7 @@ var ts; if (!exported) return undefined; var symbol = exported.symbol, kind = exported.kind; - var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + var info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); return info && __assign({ symbol: symbol, kind: kind }, info); } function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) { @@ -138575,7 +138947,7 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -138589,21 +138961,20 @@ var ts; // but we can still offer completions for it. // - `aliased.parent` will be undefined if the module is exporting `globalThis.something`, // or another expression that resolves to a global. - return getDefaultExportInfoWorker(aliased, aliased.parent, checker, compilerOptions); + return getDefaultExportInfoWorker(aliased, checker, compilerOptions); } } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + return { symbolForMeaning: defaultExport, name: ts.getNameForExportedSymbol(defaultExport, compilerOptions.target) }; } function getNameForExportDefault(symbol) { return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + var _a; if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.text; - } + return (_a = ts.tryCast(ts.skipOuterExpressions(declaration.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export"); @@ -140100,7 +140471,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + errorCodes: [ + ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ], getCodeActions: function (context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; @@ -140858,7 +141232,7 @@ var ts; var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -147161,13 +147535,13 @@ var ts; return { edits: [] }; // TODO: GH#30113 } function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); - changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include - }); + var signature = groupedReferences.signature; + var newFunctionDeclarationParams = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + if (signature) { + var newSignatureParams = ts.map(createNewParameters(signature, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); }); for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) { var call = functionCalls_1[_i]; @@ -147176,6 +147550,15 @@ var ts; changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include }); } } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes(sourceFile, ts.first(declarationOrSignature.parameters), ts.last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include + }); + } } function getGroupedReferences(functionDeclaration, program, cancellationToken) { var functionNames = getFunctionNames(functionDeclaration); @@ -147194,12 +147577,38 @@ var ts; var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation); var classSymbols = ts.map(classNames, getSymbolTargetAtLocation); var isConstructor = ts.isConstructorDeclaration(functionDeclaration); + var contextualSymbols = ts.map(functionNames, function (name) { return getSymbolForContextualType(name, checker); }); for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { var entry = referenceEntries_1[_i]; - if (entry.kind !== 1 /* Node */) { + if (entry.kind === 0 /* Span */) { groupedReferences.valid = false; continue; } + /* Declarations in object literals may be implementations of method signatures which have a different symbol from the declaration + For example: + interface IFoo { m(a: number): void } + const foo: IFoo = { m(a: number): void {} } + In these cases we get the symbol for the signature from the contextual type. + */ + if (ts.contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences.signature = entry.node.parent; + continue; + } + var call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + var contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && ts.contains(contextualSymbols, contextualSymbol)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + } /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: class A { foo(a: number, b: number) { return a + b; } } @@ -147262,6 +147671,19 @@ var ts; return symbol && ts.getSymbolTarget(symbol, checker); } } + /** + * Gets the symbol for the contextual type of the node if it is not a union or intersection. + */ + function getSymbolForContextualType(node, checker) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = checker.getContextualTypeForObjectLiteralElement(element); + var symbol = contextualType === null || contextualType === void 0 ? void 0 : contextualType.getSymbol(); + if (symbol && !(ts.getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } function entryToImportOrExport(entry) { var node = entry.node; if (ts.isImportSpecifier(node.parent) @@ -147369,6 +147791,9 @@ var ts; } return false; } + function isValidMethodSignature(node) { + return ts.isMethodSignature(node) && (ts.isInterfaceDeclaration(node.parent) || ts.isTypeLiteralNode(node.parent)); + } function isValidFunctionDeclaration(functionDeclaration, checker) { if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; @@ -147376,6 +147801,11 @@ var ts; case 251 /* FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); case 165 /* MethodDeclaration */: + if (ts.isObjectLiteralExpression(functionDeclaration.parent)) { + var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change + return (contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } return isSingleImplementation(functionDeclaration, checker); case 166 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { @@ -148998,7 +149428,7 @@ var ts; }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); throw new ts.OperationCanceledException(); } }; @@ -149028,7 +149458,7 @@ var ts; }; ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); throw new ts.OperationCanceledException(); } }; @@ -149709,8 +150139,8 @@ var ts; ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition(fileName, position) { - return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + function getDocCommentTemplateAtPosition(fileName, position, options) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -151514,9 +151944,9 @@ var ts; return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; - LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 1050818279ea0..4d1263827d964 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -2656,8 +2656,6 @@ declare namespace ts { export interface TemplateLiteralType extends InstantiableType { texts: readonly string[]; types: readonly Type[]; - freshType: TemplateLiteralType; - regularType: TemplateLiteralType; } export interface StringMappingType extends InstantiableType { symbol: Symbol; @@ -3970,6 +3968,7 @@ declare namespace ts { reScanJsxToken(): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; + reScanInvalidIdentifier(): SyntaxKind; scanJsxToken(): JsxTokenSyntaxKind; scanJsDocToken(): JSDocSyntaxKind; scan(): SyntaxKind; @@ -5556,7 +5555,7 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; + getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; /** * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. @@ -6021,11 +6020,15 @@ declare namespace ts { interface RenameInfoOptions { readonly allowRenameOfImportPath?: boolean; } + interface DocCommentTemplateOptions { + readonly generateReturnInDocTemplate?: boolean; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; displayParts: SymbolDisplayPart[]; isOptional: boolean; + isRest?: boolean; } interface SelectionRange { textSpan: TextSpan; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index d9e640b5bf532..9d3d0a2f68f64 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -3405,16 +3405,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3422,27 +3428,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); } - }, - PerformanceObserver: PerformanceObserver_1 + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); + } + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3473,7 +3478,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3504,6 +3508,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3512,7 +3519,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3525,7 +3538,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3559,40 +3579,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3636,39 +3657,41 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { + // enable the above using startTracing() +})(ts || (ts = {})); +// `tracingEnabled` should never be used directly, only through the above +/* @internal */ +(function (ts) { + var tracingEnabled; + (function (tracingEnabled) { var Mode; (function (Mode) { Mode[Mode["Project"] = 0] = "Project"; Mode[Mode["Build"] = 1] = "Build"; Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + })(Mode = tracingEnabled.Mode || (tracingEnabled.Mode = {})); var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); @@ -3677,9 +3700,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount + : mode === 2 /* Server */ ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3688,24 +3711,21 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; + ts.tracing = undefined; if (typeCatalog) { dumpTypes(typeCatalog); } @@ -3715,11 +3735,7 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; - } - tracing.isTracing = isTracing; + tracingEnabled.stopTracing = stopTracing; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3729,13 +3745,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3745,45 +3759,40 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) return; @@ -3805,7 +3814,6 @@ var ts; } function dumpTypes(types) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3885,11 +3893,15 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled = ts.tracingEnabled || (ts.tracingEnabled = {})); +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + // define after tracingEnabled is initialized + ts.startTracing = ts.tracingEnabled.startTracing; })(ts || (ts = {})); var ts; (function (ts) { @@ -4884,10 +4896,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -6318,7 +6326,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -7286,6 +7294,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7535,7 +7544,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7845,7 +7854,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -8106,6 +8115,8 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8575,6 +8586,9 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8647,6 +8661,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8719,6 +8734,7 @@ var ts; The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8987,8 +9003,9 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -10118,6 +10135,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -11120,15 +11138,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -11145,6 +11157,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11898,19 +11935,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11921,7 +11961,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -15781,6 +15821,8 @@ var ts; return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; case 203 /* CallExpression */: return node.arguments[0]; + case 256 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -17344,11 +17386,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -18033,6 +18084,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -18734,7 +18791,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -19078,6 +19135,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -19140,19 +19201,33 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + } }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); + var cache = createSymlinkCache(cwd, getCanonicalFileName); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; @@ -19162,15 +19237,15 @@ var ts; var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19554,6 +19629,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -20034,6 +20117,10 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; })(ts || (ts = {})); /* @internal */ var ts; @@ -28636,62 +28723,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 157 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28704,7 +28787,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -29580,8 +29663,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29593,6 +29676,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -34727,6 +34815,7 @@ var ts; function parseTagComments(indent, initialMargin) { var comments = []; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34752,7 +34841,8 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace comments.push(scanner.getTokenText()); break; } @@ -34809,6 +34899,7 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); @@ -34873,11 +34964,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); + var indentText = skipWhitespaceOrAsterisk(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -38301,14 +38392,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38428,7 +38519,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38440,22 +38531,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -40378,14 +40454,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -42544,6 +42620,11 @@ var ts; node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 157 /* QualifiedName */: + if (currentFlow && parent.kind === 176 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; @@ -43371,7 +43452,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -44653,6 +44734,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -45528,6 +45628,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45851,7 +45955,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -47441,7 +47545,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -49239,7 +49344,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49627,15 +49732,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49657,12 +49763,15 @@ var ts; var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -50999,7 +51108,7 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + if (func.kind === 168 /* SetAccessor */ && hasBindableName(func)) { var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); @@ -51495,8 +51604,18 @@ var ts; } if (symbol.flags & 134217728 /* ModuleExports */) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables @@ -52574,10 +52693,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -53818,12 +53937,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -54390,7 +54519,7 @@ var ts; } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); @@ -54599,7 +54728,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 167 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; @@ -54846,6 +54975,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54963,7 +55095,7 @@ var ts; } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); @@ -55565,8 +55697,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55579,7 +55718,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55690,52 +55831,40 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types, primitivesOnly) { + function removeSubtypes(types, hasObjectTypes) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return false; + } + } + count++; + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } @@ -55747,10 +55876,12 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55816,20 +55947,18 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (unionReduction & (1 /* Literal */ | 2 /* Subtype */)) { + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + } + if (unionReduction & 2 /* Subtype */) { + if (!removeSubtypes(typeSet, !!(includes & 524288 /* Object */))) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55919,7 +56048,7 @@ var ts; origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -56151,7 +56280,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -56194,7 +56323,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56244,11 +56373,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56384,7 +56519,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56488,7 +56622,8 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } @@ -56522,7 +56657,7 @@ var ts; if (prop) { if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); @@ -56856,7 +56991,7 @@ var ts; return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56932,6 +57067,21 @@ var ts; } return type; } + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 179 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 179 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; @@ -56939,9 +57089,10 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56957,16 +57108,16 @@ var ts; combinedMapper = mergeTypeMappers(mapper, context.mapper); } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56995,8 +57146,8 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; @@ -57344,11 +57495,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57358,12 +57507,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57745,15 +57894,15 @@ var ts; var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); var newAliasSymbol = aliasSymbol || type.aliasSymbol; - var id = getTypeListId(typeArguments) + (newAliasSymbol ? "@" + getSymbolId(newAliasSymbol) : ""); + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters) + (target.aliasSymbol ? "@" + getSymbolId(target.aliasSymbol) : ""), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); @@ -57911,7 +58060,7 @@ var ts; // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); @@ -57946,7 +58095,7 @@ var ts; // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing // with a combination of infinite generic types that perpetually generate new type identities. We stop // the recursion here by yielding the error type. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } @@ -58982,7 +59131,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -59433,7 +59582,7 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { @@ -59559,9 +59708,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59790,7 +59939,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59825,9 +59974,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -60070,20 +60219,17 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } + if (target.flags & 134217728 /* TemplateLiteral */ && + source.texts.length === target.texts.length && + source.types.length === target.types.length && + ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && + ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { + return -1 /* True */; } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + var constraint = getBaseConstraintOfType(source); + if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) { + resetErrorInfo(saveErrorInfo); + return result; } } else if (source.flags & 268435456 /* StringMapping */) { @@ -60342,7 +60488,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60381,8 +60527,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60395,9 +60541,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -61097,7 +61243,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -61136,7 +61282,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -61520,7 +61666,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61529,7 +61675,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -62971,7 +63117,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -63200,6 +63346,10 @@ var ts; return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); + case 157 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); case 216 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } @@ -63612,7 +63762,27 @@ var ts; if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -64013,7 +64183,7 @@ var ts; if (flowDepth === 2000) { // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -64437,10 +64607,13 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var includesNullable = strictNullChecks && maybeTypeOfKind(type, 98304 /* Nullable */); + var removeNullable = includesNullable && ts.isOptionalChain(access); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); @@ -64863,10 +65036,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -65043,7 +65221,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -65084,7 +65267,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; if (localOrExportSymbol.flags & 32 /* Class */) { @@ -66142,7 +66325,7 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. @@ -66371,6 +66554,8 @@ var ts; var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } + case 225 /* NonNullExpression */: + return getContextualType(parent, contextFlags); case 283 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); case 280 /* JsxAttribute */: @@ -66457,16 +66642,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -67803,7 +67991,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67837,7 +68029,7 @@ var ts; } else { if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); @@ -67856,8 +68048,7 @@ var ts; // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || + if (assignmentKind === 1 /* Definite */ || prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } @@ -67869,7 +68060,7 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); @@ -68517,6 +68708,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68569,8 +68769,7 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; @@ -68774,19 +68973,7 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -70155,7 +70342,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 203 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 233 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -70178,7 +70365,8 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { @@ -72263,7 +72451,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType; } function getContextNode(node) { if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { @@ -72282,7 +72470,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72366,7 +72554,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72374,7 +72562,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72627,7 +72815,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72637,7 +72825,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -73289,7 +73477,7 @@ var ts; if (ts.isPrivateIdentifier(node.name)) { error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; @@ -73373,7 +73561,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -74462,7 +74650,7 @@ var ts; // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74667,11 +74855,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -75155,10 +75347,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -76255,7 +76447,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -77181,7 +77373,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -77373,7 +77565,7 @@ var ts; error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77965,7 +78157,7 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -78001,15 +78193,15 @@ var ts; break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -78928,7 +79120,7 @@ var ts; // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true return !!(target.flags & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78936,13 +79128,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -79181,8 +79374,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -80332,19 +80524,31 @@ var ts; return true; } if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 166 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } @@ -85065,8 +85269,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -85200,7 +85403,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -86137,6 +86340,11 @@ var ts; if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } @@ -96360,7 +96568,7 @@ var ts; var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; - expression = createExportExpression(exportName, expression); + expression = factory.createParenthesizedExpression(createExportExpression(exportName, expression)); } return expression; } @@ -98012,7 +98220,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -98110,7 +98319,7 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { @@ -98403,11 +98612,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98490,6 +98701,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98559,8 +98771,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98584,8 +98796,8 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { @@ -98598,12 +98810,12 @@ var ts; } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; @@ -99300,7 +99512,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99469,6 +99683,8 @@ var ts; } } case 252 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99579,6 +99795,8 @@ var ts; if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99960,9 +100178,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -100558,15 +100776,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -105969,7 +106187,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -106303,7 +106521,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106379,15 +106597,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106425,13 +106643,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106439,7 +106657,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106562,19 +106780,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106582,12 +106800,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -107059,7 +107277,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -107068,7 +107286,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -107114,9 +107332,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107777,13 +107995,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -108042,9 +108260,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -108350,6 +108568,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108879,7 +109100,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108896,7 +109117,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -110625,6 +110846,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -111428,12 +111650,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111447,40 +111665,47 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_15 = ts.forEach(targets, function (p) { return !ts.containsIgnoredPath(p) && cb(p, referenceRedirect === p); }); if (result_15) return result_15; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); var result_16 = cb(option, target === referenceRedirect); if (result_16) return result_16; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111525,9 +111750,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + var state_8 = _loop_24(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_8 === "break") break; } if (allFileNames.size) { @@ -117504,7 +117729,7 @@ var ts; // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = getQuotePreference(sourceFile, preferences); var quoted = JSON.stringify(text); - return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'" : quoted; + return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted; } ts.quote = quote; function isEqualityOperatorKind(kind) { @@ -117871,9 +118096,9 @@ var ts; } ts.firstOrOnly = firstOrOnly; function getNameForExportedSymbol(symbol, scriptTarget) { - if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { + if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); } return symbol.name; @@ -120388,6 +120613,7 @@ var ts; } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) { var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -120875,7 +121101,7 @@ var ts; keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } @@ -120989,13 +121215,34 @@ var ts; ? 6 /* TypeAssertionKeywords */ : 7 /* TypeKeywords */; } + var variableDeclaration = getVariableDeclaration(location); ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { return true; } - symbol = ts.skipAlias(symbol, typeChecker); + // Filter out variables from their own initializers + // `const a = /* no 'a' here */` + if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { + return false; + } + // External modules can have global export declarations that will be + // available as global keywords in all scopes. But if the external module + // already has an explicit export and user only wants to user explicit + // module imports then the global keywords will be filtered out so auto + // import suggestions will win in the completion + var symbolOrigin = ts.skipAlias(symbol, typeChecker); + // We only want to filter out the global keywords + // Auto Imports are not available for scripts so this conditional is always false + if (!!sourceFile.externalModuleIndicator + && !compilerOptions.allowUmdGlobalAccess + && symbolToSortTextMap[ts.getSymbolId(symbol)] === SortText.GlobalsOrKeywords + && symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions) { + return false; + } + // Continue with origin symbol + symbol = symbolOrigin; // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); @@ -121009,6 +121256,18 @@ var ts; return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); }); } + function getVariableDeclaration(property) { + var variableDeclaration = ts.findAncestor(property, function (node) { + return ts.isFunctionBlock(node) || isArrowFunctionBody(node) || ts.isBindingPattern(node) + ? "quit" + : ts.isVariableDeclaration(node); + }); + return variableDeclaration; + } + function isArrowFunctionBody(node) { + return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node; + } + ; function isTypeOnlyCompletion() { return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && @@ -121268,18 +121527,19 @@ var ts; } return false; } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + function isNewIdentifierDefinitionLocation() { + if (contextToken) { + var containingNodeKind = contextToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { + switch (keywordForNode(contextToken)) { case 27 /* CommaToken */: return containingNodeKind === 203 /* CallExpression */ // func( a, | || containingNodeKind === 166 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ || containingNodeKind === 204 /* NewExpression */ // new C(a, | || containingNodeKind === 199 /* ArrayLiteralExpression */ // [a, | || containingNodeKind === 216 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 174 /* FunctionType */; // var x: (s: string, list| + || containingNodeKind === 174 /* FunctionType */ // var x: (s: string, list| + || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { x, | case 20 /* OpenParenToken */: return containingNodeKind === 203 /* CallExpression */ // func( | || containingNodeKind === 166 /* Constructor */ // constructor( | @@ -121296,7 +121556,8 @@ var ts; case 24 /* DotToken */: return containingNodeKind === 256 /* ModuleDeclaration */; // module A.| case 18 /* OpenBraceToken */: - return containingNodeKind === 252 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 252 /* ClassDeclaration */ // class A { | + || containingNodeKind === 200 /* ObjectLiteralExpression */; // const obj = { | case 62 /* EqualsToken */: return containingNodeKind === 249 /* VariableDeclaration */ // const x = a| || containingNodeKind === 216 /* BinaryExpression */; // x = a| @@ -126682,7 +126943,7 @@ var ts; * @param position The (character-indexed) position in the file where the check should * be performed. */ - function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { @@ -126694,7 +126955,7 @@ var ts; if (!existingDocComment && tokenStart < position) { return undefined; } - var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); if (!commentOwnerInfo) { return undefined; } @@ -126744,10 +127005,10 @@ var ts; function returnsDocComment(indentationStr, newLine) { return indentationStr + " * @returns" + newLine; } - function getCommentOwnerInfo(tokenAtPos) { - return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + function getCommentOwnerInfo(tokenAtPos, options) { + return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); }); } - function getCommentOwnerInfoWorker(commentOwner) { + function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { case 251 /* FunctionDeclaration */: case 208 /* FunctionExpression */: @@ -126756,9 +127017,9 @@ var ts; case 164 /* MethodSignature */: case 209 /* ArrowFunction */: var host = commentOwner; - return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host) }; + return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; case 288 /* PropertyAssignment */: - return getCommentOwnerInfoWorker(commentOwner.initializer); + return getCommentOwnerInfoWorker(commentOwner.initializer, options); case 252 /* ClassDeclaration */: case 253 /* InterfaceDeclaration */: case 162 /* PropertySignature */: @@ -126773,7 +127034,7 @@ var ts; ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1) } + ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } : { commentOwner: commentOwner }; } case 297 /* SourceFile */: @@ -126784,26 +127045,27 @@ var ts; // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. return commentOwner.parent.kind === 256 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 233 /* ExpressionStatement */: - return getCommentOwnerInfoWorker(commentOwner.expression); + return getCommentOwnerInfoWorker(commentOwner.expression, options); case 216 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } return ts.isFunctionLike(be.right) - ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right) } + ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner: commentOwner }; } case 163 /* PropertyDeclaration */: var init = commentOwner.initializer; if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { - return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init) }; + return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; } } } - function hasReturn(node) { - return ts.isArrowFunction(node) && ts.isExpression(node.body) - || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; }); + function hasReturn(node, options) { + return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && + (ts.isArrowFunction(node) && ts.isExpression(node.body) + || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { while (rightHandSide.kind === 207 /* ParenthesizedExpression */) { @@ -127101,6 +127363,16 @@ var ts; addChildrenRecursively(child); endNode(); } + function addNodeWithRecursiveInitializer(node) { + if (node.initializer && isFunctionOrClassExpression(node.initializer)) { + startNode(node); + ts.forEachChild(node.initializer, addChildrenRecursively); + endNode(); + } + else { + addNodeWithRecursiveChild(node, node.initializer); + } + } /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node) { var _a; @@ -127130,6 +127402,10 @@ var ts; } break; case 163 /* PropertyDeclaration */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveInitializer(node); + } + break; case 162 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); @@ -127168,21 +127444,16 @@ var ts; break; case 198 /* BindingElement */: case 288 /* PropertyAssignment */: - case 249 /* VariableDeclaration */: - var _e = node, name = _e.name, initializer = _e.initializer; - if (ts.isBindingPattern(name)) { - addChildrenRecursively(name); - } - else if (initializer && isFunctionOrClassExpression(initializer)) { - // Add a node for the VariableDeclaration, but not for the initializer. - startNode(node); - ts.forEachChild(initializer, addChildrenRecursively); - endNode(); + case 249 /* VariableDeclaration */: { + var child = node; + if (ts.isBindingPattern(child.name)) { + addChildrenRecursively(child.name); } else { - addNodeWithRecursiveChild(node, initializer); + addNodeWithRecursiveInitializer(child); } break; + } case 251 /* FunctionDeclaration */: var nameNode = node.name; // If we see a function declaration track as a possible ES5 class @@ -127197,8 +127468,8 @@ var ts; break; case 255 /* EnumDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } @@ -127209,8 +127480,8 @@ var ts; case 221 /* ClassExpression */: case 253 /* InterfaceDeclaration */: startNode(node); - for (var _h = 0, _j = node.members; _h < _j.length; _h++) { - var member = _j[_h]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); @@ -127293,7 +127564,7 @@ var ts; defineCall.arguments[0] : defineCall.arguments[0].expression; var memberName = defineCall.arguments[1]; - var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1]; + var _j = startNestedNodes(node, className), depth = _j[0], classNameIdentifier = _j[1]; startNode(node, classNameIdentifier); startNode(node, ts.setTextRange(ts.factory.createIdentifier(memberName.text), memberName)); addChildrenRecursively(node.arguments[2]); @@ -130225,7 +130496,19 @@ var ts; itemsSeen += item.length; } ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. - return { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var help = { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var selected = help.items[selectedItemIndex]; + if (selected.isVariadic) { + var firstRest = ts.findIndex(selected.parameters, function (p) { return !!p.isRest; }); + if (-1 < firstRest && firstRest < selected.parameters.length - 1) { + // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL + help.argumentIndex = selected.parameters.length; + } + else { + help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1); + } + } + return help; } function createTypeHelpItems(symbol, _a, sourceFile, checker) { var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; @@ -130307,14 +130590,15 @@ var ts; printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); - return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + var isRest = !!(parameter.checkFlags & 32768 /* RestParameter */); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional, isRest: isRest }; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false, isRest: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -130577,7 +130861,7 @@ var ts; return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && - hasReturnStatementWithPromiseHandler(node.body) && + hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker); } function returnsPromise(node, checker) { @@ -130589,23 +130873,23 @@ var ts; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - function hasReturnStatementWithPromiseHandler(body) { - return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + function hasReturnStatementWithPromiseHandler(body, checker) { + return !!ts.forEachReturnStatement(body, function (statement) { return isReturnStatementWithFixablePromiseHandler(statement, checker); }); } - function isReturnStatementWithFixablePromiseHandler(node) { - return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + function isReturnStatementWithFixablePromiseHandler(node, checker) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - function isFixablePromiseHandler(node) { + function isFixablePromiseHandler(node, checker) { // ensure outermost call exists and is a promise handler - if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + if (!isPromiseHandler(node) || !node.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } // ensure all chained calls are valid var currentNode = node.expression; while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { - if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } currentNode = currentNode.expression; @@ -130628,7 +130912,7 @@ var ts; }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts - function isFixablePromiseArgument(arg) { + function isFixablePromiseArgument(arg, checker) { switch (arg.kind) { case 251 /* FunctionDeclaration */: case 208 /* FunctionExpression */: @@ -130636,8 +130920,16 @@ var ts; visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); // falls through case 103 /* NullKeyword */: - case 78 /* Identifier */: // identifier includes undefined return true; + case 78 /* Identifier */: + case 201 /* PropertyAccessExpression */: { + var symbol = checker.getSymbolAtLocation(arg); + if (!symbol) { + return false; + } + return checker.isUndefinedSymbol(symbol) || + ts.some(ts.skipAlias(symbol, checker).declarations, function (d) { return ts.isFunctionLike(d) || ts.hasInitializer(d) && !!d.initializer && ts.isFunctionLike(d.initializer); }); + } default: return false; } @@ -132978,14 +133270,17 @@ var ts; processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } if (!formattingScanner.isOnToken()) { + var indentation = formatting.SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false) + ? initialIndentation + options.indentSize + : initialIndentation; var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); - if (options.trimTrailingWhitespace !== false) { - trimTrailingWhitespacesForRemainingRange(); - } + indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); } } + if (options.trimTrailingWhitespace !== false) { + trimTrailingWhitespacesForRemainingRange(); + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -133032,10 +133327,9 @@ var ts; // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; } - else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; - } - else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { @@ -133123,6 +133417,7 @@ var ts; case 275 /* JsxOpeningElement */: case 276 /* JsxClosingElement */: case 274 /* JsxSelfClosingElement */: + case 223 /* ExpressionWithTypeArguments */: return false; } break; @@ -133924,6 +134219,7 @@ var ts; } SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var _a; var parent = current.parent; // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if // * parent and child nodes start on the same line, or @@ -133939,7 +134235,25 @@ var ts; childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + var firstListChild = (_a = getContainingList(current, sourceFile)) === null || _a === void 0 ? void 0 : _a[0]; + // A list indents its children if the children begin on a later line than the list itself: + // + // f1( L0 - List start + // { L1 - First child start: indented, along with all other children + // prop: 0 + // }, + // { + // prop: 1 + // } + // ) + // + // f2({ L0 - List start and first child start: children are not indented. + // prop: 0 Object properties are indented only one level, because the list + // }, { itself contributes nothing. + // prop: 1 L3 - The indentation of the second object literal is best understood by + // }) looking at the relationship between the list and *first* list item. + var listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line; + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -134052,6 +134366,49 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + // A multiline conditional typically increases the indentation of its whenTrue and whenFalse children: + // + // condition + // ? whenTrue + // : whenFalse; + // + // However, that indentation does not apply if the subexpressions themselves span multiple lines, + // applying their own indentation: + // + // (() => { + // return complexCalculationForCondition(); + // })() ? { + // whenTrue: 'multiline object literal' + // } : ( + // whenFalse('multiline parenthesized expression') + // ); + // + // In these cases, we must discard the indentation increase that would otherwise be applied to the + // whenTrue and whenFalse children to avoid double-indenting their contents. To identify this scenario, + // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse + // branch beginning on the line that the whenTrue branch ends. + function childIsUnindentedBranchOfConditionalExpression(parent, child, childStartLine, sourceFile) { + if (ts.isConditionalExpression(parent) && (child === parent.whenTrue || child === parent.whenFalse)) { + var conditionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.condition.end).line; + if (child === parent.whenTrue) { + return childStartLine === conditionEndLine; + } + else { + // On the whenFalse side, we have to look at the whenTrue side, because if that one was + // indented, whenFalse must also be indented: + // + // const y = true + // ? 1 : ( L1: whenTrue indented because it's on a new line + // 0 L2: indented two stops, one because whenTrue was indented + // ); and one because of the parentheses spanning multiple lines + var trueStartLine = getStartLineAndCharacterForNode(parent.whenTrue, sourceFile).line; + var trueEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.whenTrue.end).line; + return conditionEndLine === trueStartLine && trueEndLine === childStartLine; + } + } + return false; + } + SmartIndenter.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) { if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) @@ -134297,7 +134654,7 @@ var ts; if (childKind === 177 /* TypeLiteral */ || childKind === 179 /* TupleType */) { return false; } - // falls through + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -135780,7 +136137,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + errorCodes: [ + ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], getCodeActions: function (context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { @@ -136792,7 +137152,7 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); - var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; @@ -136818,10 +137178,10 @@ var ts; _loop_12(returnStatement); } } - function getReturnStatementsWithPromiseHandlers(body) { + function getReturnStatementsWithPromiseHandlers(body, checker) { var res = []; ts.forEachReturnStatement(body, function (ret) { - if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + if (ts.isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; @@ -137070,6 +137430,7 @@ var ts; case 103 /* NullKeyword */: // do not produce a transformed statement for a null argument break; + case 201 /* PropertyAccessExpression */: case 78 /* Identifier */: // identifier includes undefined if (!argName) { // undefined was argument passed to promise handler @@ -137103,7 +137464,7 @@ var ts; var statement = _f[_i]; if (ts.isReturnStatement(statement)) { seenReturnStatement = true; - if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + if (ts.isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -137120,7 +137481,7 @@ var ts; : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); } else { - var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; + var innerRetStmts = ts.isFixablePromiseHandler(funcBody, transformer.checker) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return innerCbBody; @@ -137213,6 +137574,9 @@ var ts; else if (ts.isIdentifier(funcNode)) { name = getMapEntryOrDefault(funcNode); } + else if (ts.isPropertyAccessExpression(funcNode) && ts.isIdentifier(funcNode.name)) { + name = getMapEntryOrDefault(funcNode.name); + } // return undefined argName when arg is null or undefined // eslint-disable-next-line no-in-operator if (!name || "identifier" in name && name.identifier.text === "undefined") { @@ -138203,7 +138567,7 @@ var ts; : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; + var moduleSpecifier = getBestFix(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences), sourceFile, program, host).moduleSpecifier; var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } @@ -138211,7 +138575,7 @@ var ts; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); + return getBestFix(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, program, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -138390,8 +138754,7 @@ var ts; function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); - var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + return ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences) .map(function (moduleSpecifier) { @@ -138401,18 +138764,6 @@ var ts; : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; }); }); - // Sort by presence in package.json, then shortest paths first - return ts.sort(choicesForEachExportingModule, function (a, b) { - var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier); - var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier); - if (allowsImportingA && !allowsImportingB) { - return -1; - } - if (allowsImportingB && !allowsImportingA) { - return 1; - } - return a.moduleSpecifier.length - b.moduleSpecifier.length; - }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); @@ -138433,7 +138784,28 @@ var ts; var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, context.host) }); + } + function sortFixes(fixes, sourceFile, program, host) { + var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier); }); + } + function getBestFix(fixes, sourceFile, program, host) { + // These will always be placed first if available, and are better than other kinds + if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { + return fixes[0]; + } + var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; + return fixes.reduce(function (best, fix) { + return compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + }); + } + function compareModuleSpecifiers(a, b, allowsImportingSpecifier) { + if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { + return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + } + return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; @@ -138540,7 +138912,7 @@ var ts; if (!exported) return undefined; var symbol = exported.symbol, kind = exported.kind; - var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + var info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); return info && __assign({ symbol: symbol, kind: kind }, info); } function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) { @@ -138575,7 +138947,7 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -138589,21 +138961,20 @@ var ts; // but we can still offer completions for it. // - `aliased.parent` will be undefined if the module is exporting `globalThis.something`, // or another expression that resolves to a global. - return getDefaultExportInfoWorker(aliased, aliased.parent, checker, compilerOptions); + return getDefaultExportInfoWorker(aliased, checker, compilerOptions); } } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + return { symbolForMeaning: defaultExport, name: ts.getNameForExportedSymbol(defaultExport, compilerOptions.target) }; } function getNameForExportDefault(symbol) { return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + var _a; if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.text; - } + return (_a = ts.tryCast(ts.skipOuterExpressions(declaration.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export"); @@ -140100,7 +140471,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + errorCodes: [ + ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ], getCodeActions: function (context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; @@ -140858,7 +141232,7 @@ var ts; var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -147161,13 +147535,13 @@ var ts; return { edits: [] }; // TODO: GH#30113 } function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); - changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include - }); + var signature = groupedReferences.signature; + var newFunctionDeclarationParams = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + if (signature) { + var newSignatureParams = ts.map(createNewParameters(signature, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); }); for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) { var call = functionCalls_1[_i]; @@ -147176,6 +147550,15 @@ var ts; changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include }); } } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes(sourceFile, ts.first(declarationOrSignature.parameters), ts.last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include + }); + } } function getGroupedReferences(functionDeclaration, program, cancellationToken) { var functionNames = getFunctionNames(functionDeclaration); @@ -147194,12 +147577,38 @@ var ts; var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation); var classSymbols = ts.map(classNames, getSymbolTargetAtLocation); var isConstructor = ts.isConstructorDeclaration(functionDeclaration); + var contextualSymbols = ts.map(functionNames, function (name) { return getSymbolForContextualType(name, checker); }); for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { var entry = referenceEntries_1[_i]; - if (entry.kind !== 1 /* Node */) { + if (entry.kind === 0 /* Span */) { groupedReferences.valid = false; continue; } + /* Declarations in object literals may be implementations of method signatures which have a different symbol from the declaration + For example: + interface IFoo { m(a: number): void } + const foo: IFoo = { m(a: number): void {} } + In these cases we get the symbol for the signature from the contextual type. + */ + if (ts.contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences.signature = entry.node.parent; + continue; + } + var call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + var contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && ts.contains(contextualSymbols, contextualSymbol)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + } /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: class A { foo(a: number, b: number) { return a + b; } } @@ -147262,6 +147671,19 @@ var ts; return symbol && ts.getSymbolTarget(symbol, checker); } } + /** + * Gets the symbol for the contextual type of the node if it is not a union or intersection. + */ + function getSymbolForContextualType(node, checker) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = checker.getContextualTypeForObjectLiteralElement(element); + var symbol = contextualType === null || contextualType === void 0 ? void 0 : contextualType.getSymbol(); + if (symbol && !(ts.getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } function entryToImportOrExport(entry) { var node = entry.node; if (ts.isImportSpecifier(node.parent) @@ -147369,6 +147791,9 @@ var ts; } return false; } + function isValidMethodSignature(node) { + return ts.isMethodSignature(node) && (ts.isInterfaceDeclaration(node.parent) || ts.isTypeLiteralNode(node.parent)); + } function isValidFunctionDeclaration(functionDeclaration, checker) { if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; @@ -147376,6 +147801,11 @@ var ts; case 251 /* FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); case 165 /* MethodDeclaration */: + if (ts.isObjectLiteralExpression(functionDeclaration.parent)) { + var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change + return (contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } return isSingleImplementation(functionDeclaration, checker); case 166 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { @@ -148998,7 +149428,7 @@ var ts; }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); throw new ts.OperationCanceledException(); } }; @@ -149028,7 +149458,7 @@ var ts; }; ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); throw new ts.OperationCanceledException(); } }; @@ -149709,8 +150139,8 @@ var ts; ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition(fileName, position) { - return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + function getDocCommentTemplateAtPosition(fileName, position, options) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -151514,9 +151944,9 @@ var ts; return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; - LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index f5ac11e6b45f9..f33fba5875463 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -3200,16 +3200,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3217,27 +3223,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); + } + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); } - }, - PerformanceObserver: PerformanceObserver_1 + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3268,7 +3273,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3299,6 +3303,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3307,7 +3314,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3320,7 +3333,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3354,40 +3374,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3431,39 +3452,41 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { + // enable the above using startTracing() +})(ts || (ts = {})); +// `tracingEnabled` should never be used directly, only through the above +/* @internal */ +(function (ts) { + var tracingEnabled; + (function (tracingEnabled) { var Mode; (function (Mode) { Mode[Mode["Project"] = 0] = "Project"; Mode[Mode["Build"] = 1] = "Build"; Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + })(Mode = tracingEnabled.Mode || (tracingEnabled.Mode = {})); var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); @@ -3472,9 +3495,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount + : mode === 2 /* Server */ ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3483,24 +3506,21 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; + ts.tracing = undefined; if (typeCatalog) { dumpTypes(typeCatalog); } @@ -3510,11 +3530,7 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; - } - tracing.isTracing = isTracing; + tracingEnabled.stopTracing = stopTracing; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3524,13 +3540,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3540,45 +3554,40 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) return; @@ -3600,7 +3609,6 @@ var ts; } function dumpTypes(types) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3680,11 +3688,15 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled = ts.tracingEnabled || (ts.tracingEnabled = {})); +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + // define after tracingEnabled is initialized + ts.startTracing = ts.tracingEnabled.startTracing; })(ts || (ts = {})); var ts; (function (ts) { @@ -4679,10 +4691,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -6113,7 +6121,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -7081,6 +7089,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7330,7 +7339,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7640,7 +7649,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -7901,6 +7910,8 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8370,6 +8381,9 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8442,6 +8456,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8514,6 +8529,7 @@ var ts; The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8782,8 +8798,9 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -9913,6 +9930,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -10915,15 +10933,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -10940,6 +10952,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11693,19 +11730,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11716,7 +11756,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -15576,6 +15616,8 @@ var ts; return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; case 203 /* CallExpression */: return node.arguments[0]; + case 256 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -17139,11 +17181,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -17828,6 +17879,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -18529,7 +18586,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -18873,6 +18930,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -18935,19 +18996,33 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + } }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); + var cache = createSymlinkCache(cwd, getCanonicalFileName); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; @@ -18957,15 +19032,15 @@ var ts; var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19349,6 +19424,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -19829,6 +19912,10 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; })(ts || (ts = {})); /* @internal */ var ts; @@ -28431,62 +28518,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 157 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28499,7 +28582,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -29375,8 +29458,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29388,6 +29471,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -34522,6 +34610,7 @@ var ts; function parseTagComments(indent, initialMargin) { var comments = []; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34547,7 +34636,8 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace comments.push(scanner.getTokenText()); break; } @@ -34604,6 +34694,7 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); @@ -34668,11 +34759,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); + var indentText = skipWhitespaceOrAsterisk(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -38096,14 +38187,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38223,7 +38314,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38235,22 +38326,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -40173,14 +40249,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -42339,6 +42415,11 @@ var ts; node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 157 /* QualifiedName */: + if (currentFlow && parent.kind === 176 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; @@ -43166,7 +43247,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -44448,6 +44529,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -45323,6 +45423,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45646,7 +45750,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -47236,7 +47340,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -49034,7 +49139,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49422,15 +49527,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49452,12 +49558,15 @@ var ts; var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -50794,7 +50903,7 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + if (func.kind === 168 /* SetAccessor */ && hasBindableName(func)) { var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); @@ -51290,8 +51399,18 @@ var ts; } if (symbol.flags & 134217728 /* ModuleExports */) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables @@ -52369,10 +52488,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -53613,12 +53732,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -54185,7 +54314,7 @@ var ts; } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); @@ -54394,7 +54523,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 167 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; @@ -54641,6 +54770,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54758,7 +54890,7 @@ var ts; } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); @@ -55360,8 +55492,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55374,7 +55513,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55485,52 +55626,40 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types, primitivesOnly) { + function removeSubtypes(types, hasObjectTypes) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return false; + } + } + count++; + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } @@ -55542,10 +55671,12 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55611,20 +55742,18 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (unionReduction & (1 /* Literal */ | 2 /* Subtype */)) { + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + } + if (unionReduction & 2 /* Subtype */) { + if (!removeSubtypes(typeSet, !!(includes & 524288 /* Object */))) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55714,7 +55843,7 @@ var ts; origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -55946,7 +56075,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -55989,7 +56118,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56039,11 +56168,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56179,7 +56314,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56283,7 +56417,8 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } @@ -56317,7 +56452,7 @@ var ts; if (prop) { if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); @@ -56651,7 +56786,7 @@ var ts; return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56727,6 +56862,21 @@ var ts; } return type; } + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 179 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 179 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; @@ -56734,9 +56884,10 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56752,16 +56903,16 @@ var ts; combinedMapper = mergeTypeMappers(mapper, context.mapper); } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56790,8 +56941,8 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; @@ -57139,11 +57290,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57153,12 +57302,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57540,15 +57689,15 @@ var ts; var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); var newAliasSymbol = aliasSymbol || type.aliasSymbol; - var id = getTypeListId(typeArguments) + (newAliasSymbol ? "@" + getSymbolId(newAliasSymbol) : ""); + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters) + (target.aliasSymbol ? "@" + getSymbolId(target.aliasSymbol) : ""), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); @@ -57706,7 +57855,7 @@ var ts; // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); @@ -57741,7 +57890,7 @@ var ts; // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing // with a combination of infinite generic types that perpetually generate new type identities. We stop // the recursion here by yielding the error type. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } @@ -58777,7 +58926,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -59228,7 +59377,7 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { @@ -59354,9 +59503,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59585,7 +59734,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59620,9 +59769,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -59865,20 +60014,17 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } + if (target.flags & 134217728 /* TemplateLiteral */ && + source.texts.length === target.texts.length && + source.types.length === target.types.length && + ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && + ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { + return -1 /* True */; } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + var constraint = getBaseConstraintOfType(source); + if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) { + resetErrorInfo(saveErrorInfo); + return result; } } else if (source.flags & 268435456 /* StringMapping */) { @@ -60137,7 +60283,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60176,8 +60322,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60190,9 +60336,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -60892,7 +61038,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -60931,7 +61077,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -61315,7 +61461,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61324,7 +61470,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -62766,7 +62912,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -62995,6 +63141,10 @@ var ts; return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); + case 157 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); case 216 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } @@ -63407,7 +63557,27 @@ var ts; if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -63808,7 +63978,7 @@ var ts; if (flowDepth === 2000) { // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -64232,10 +64402,13 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var includesNullable = strictNullChecks && maybeTypeOfKind(type, 98304 /* Nullable */); + var removeNullable = includesNullable && ts.isOptionalChain(access); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); @@ -64658,10 +64831,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -64838,7 +65016,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -64879,7 +65062,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; if (localOrExportSymbol.flags & 32 /* Class */) { @@ -65937,7 +66120,7 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. @@ -66166,6 +66349,8 @@ var ts; var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } + case 225 /* NonNullExpression */: + return getContextualType(parent, contextFlags); case 283 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); case 280 /* JsxAttribute */: @@ -66252,16 +66437,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -67598,7 +67786,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67632,7 +67824,7 @@ var ts; } else { if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); @@ -67651,8 +67843,7 @@ var ts; // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || + if (assignmentKind === 1 /* Definite */ || prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } @@ -67664,7 +67855,7 @@ var ts; // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); @@ -68312,6 +68503,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68364,8 +68564,7 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; @@ -68569,19 +68768,7 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -69950,7 +70137,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 203 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 233 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -69973,7 +70160,8 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { @@ -72058,7 +72246,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType; } function getContextNode(node) { if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { @@ -72077,7 +72265,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72161,7 +72349,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72169,7 +72357,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72422,7 +72610,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72432,7 +72620,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -73084,7 +73272,7 @@ var ts; if (ts.isPrivateIdentifier(node.name)) { error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; @@ -73168,7 +73356,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -74257,7 +74445,7 @@ var ts; // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74462,11 +74650,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -74950,10 +75142,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -76050,7 +76242,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -76976,7 +77168,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -77168,7 +77360,7 @@ var ts; error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77760,7 +77952,7 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -77796,15 +77988,15 @@ var ts; break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -78723,7 +78915,7 @@ var ts; // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true return !!(target.flags & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78731,13 +78923,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -78976,8 +79169,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -80127,19 +80319,31 @@ var ts; return true; } if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 166 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } @@ -84860,8 +85064,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -84995,7 +85198,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -85932,6 +86135,11 @@ var ts; if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } @@ -96155,7 +96363,7 @@ var ts; var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; - expression = createExportExpression(exportName, expression); + expression = factory.createParenthesizedExpression(createExportExpression(exportName, expression)); } return expression; } @@ -97807,7 +98015,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -97905,7 +98114,7 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { @@ -98198,11 +98407,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98285,6 +98496,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98354,8 +98566,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98379,8 +98591,8 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { @@ -98393,12 +98605,12 @@ var ts; } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; @@ -99095,7 +99307,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99264,6 +99478,8 @@ var ts; } } case 252 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99374,6 +99590,8 @@ var ts; if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99755,9 +99973,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -100353,15 +100571,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -105764,7 +105982,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -106098,7 +106316,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106174,15 +106392,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106220,13 +106438,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106234,7 +106452,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106357,19 +106575,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106377,12 +106595,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -106854,7 +107072,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -106863,7 +107081,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -106909,9 +107127,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107572,13 +107790,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -107837,9 +108055,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -108145,6 +108363,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108674,7 +108895,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108691,7 +108912,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -110420,6 +110641,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -111223,12 +111445,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111242,40 +111460,47 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_15 = ts.forEach(targets, function (p) { return !ts.containsIgnoredPath(p) && cb(p, referenceRedirect === p); }); if (result_15) return result_15; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); var result_16 = cb(option, target === referenceRedirect); if (result_16) return result_16; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111320,9 +111545,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + var state_8 = _loop_24(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_8 === "break") break; } if (allFileNames.size) { diff --git a/package.json b/package.json index 03343354a1fe0..7588a51cfc211 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "https://www.typescriptlang.org/", - "version": "4.2.0-beta", + "version": "4.2.1-rc", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [